Rails: Nested Resoucesを削除するには

PostとCommentのModelがあってPostが複数のCommentを持ってます。やりたいのはPostの表示画面(show view)でCommentを削除するリンクを作成ことです。

前提

まずPostとCommentのModel、及びroutes.rbの設定を理解しましょう。

# post model
has_many :comments

# comment model
belongs_to :post

# routes.rb
resources :posts do
  resources :comments
end

方法

Viewのerbファイルでは下記のようなリンクを作成します。

<% @article.comments.each do |comment|
  <%= comment.content %>
  <%= link_to "Delete", article_comment_path(@article, :comment_id => comment), :method => :delete %>
<% end %>

これはcomments_controllerのdestroyアクションを呼ぶのでdestroy actionを作成する必要があります。

# in comments_controller.rb

def destroy
  comment = Comment.find(params[:comment_id]
  comment.destroy
  redirect_to request.referer
end

:comment_idはviewで設定するパラメータ名と一致すればOKです。

Qihuan Piao

朴 起煥

中国育ち、東京暮らし。読んだり書いたり、時には考え込んだり。親になってから5年ほど、ブログ(とその他もろもろ)は完全停止していたけど、気づけばまた書いている。ここにはそんな寄り道の記録を書いています。結論が出ない話も多いけど、それもまたよし。