我尝试删除与comment
相关联的location
。这些是我的模特:
location.rb
class Location < ApplicationRecord
has_many :comments, dependent: :destroy
end
comment.rb
class Comment < ApplicationRecord
belongs_to :location
end
CommentsController.rb
def destroy
@location = Location.find(params[:location_id])
@comment = @location.comments.find(params[:id])
@comment.destroy
redirect_to locations_path
end
comment.html.erb
<% if user_signed_in? %>
<p>
<%= link_to 'Delete',
location_comment_path
[comment.location, comment],
method: :delete,
class: "button",
data: { confirm: 'Are you sure?' } %>
</p>
<% end %>
我希望已登录的用户删除他们的评论并重定向到位置表单,但它没有发生。
相反,我收到了这个错误:
ActiveRecord :: RecordNotFound(无法找到评论&#39; id&#39; = 1 [WHERE&#34;评论&#34;。&#34; location_id&#34; =?]): app / controllers / comments_controller.rb:21:在`destroy&#39;
答案 0 :(得分:0)
如果您在控制器中设置了位置和注释,则可以在视图中使用它们。
假设通过索引方法呈现部分,则:
# app/controllers/comments_controller.rb
def index
@comments = Comment.all
@location = Location.find params[:location_id]
end
然后在部分中,并传递两个对象,您可以访问路径:
<%= link_to 'Destroy',
location_comment_path(@location, comment),
method: :delete, data: { confirm: 'Are you sure?' } %></td>
注意使用parens而不是方括号。
如果已经设置了要销毁的评论,那么您不必担心该位置,只需销毁评论并重定向:
def destroy
Comment.find(params[:id]).destroy
redirect_to location_comments_path
end