当我尝试删除注释时,注释没有从数据库中删除,并且还有一个错误未定义的方法`comment_path' ...
_comment.html.erb
<% if current_user?(comment.user) %>
<%= link_to "delete", comment, method: :delete %>
<% end %>
comments_controller.rb
def destroy
@comment.destroy
flash[:success] = "Micropost deleted"
redirect_to request.referrer || root_url
end
microposts_controller.rb
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
@comments = @micropost.comments
end
的routes.rb
resources :microposts do
resources :comments
end
答案 0 :(得分:2)
link_to(
"delete",
microposts_comment_path(comment.micropost, comment),
method: :delete
)
或
link_to(
'Delete Comment',
[comment.micropost, comment],
method: :delete,
data: { confirm: 'Are you sure?' }
)
答案 1 :(得分:1)
您的comments
嵌套在microposts
的范围内。
要使其工作,您必须在锚标记中提供微博。
示例:强>
link_to "Delete Comment", [comment.micropost, comment], method: :delete
# OR
link_to "Delete Comment", microposts_comment_path(comment.micropost, comment), method: :delete
答案 2 :(得分:1)
由于您拥有嵌套资源,因此必须执行以下操作:
1.在您的控制器中:
# DELETE /microposts/:micropost_id/comments/1
def destroy
#1st you retrieve the micropost thanks to params[:micropost_id]
micropost = Micropost.find(params[:micropost_id])
#2nd you retrieve the comment thanks to params[:id]
@comment = micropost.comments.find(params[:id])
@comment.destroy
flash[:success] = "Micropost deleted"
redirect_to request.referrer || root_url
end
2.在您看来,替换
<%= link_to "delete", comment, method: :delete %>
使用:
<%= link_to "delete", [comment.micropost, comment], method: :delete %>