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です。
Tags: rails
You can leave a response, or trackback from your own site.
