在Rails应用中将comments_id传递给控制器
问题描述:
我无法编辑/删除基本Rails MVC中的注释,但是我遇到的麻烦是comments_controller查找user_id而不是comments_id,因为user_id是外部键。我的假设是,Comment.find(params [:id])会导致comments_id,但这不是情况。在Rails应用中将comments_id传递给控制器
这是我comments_controller的最后一部分:
def edit
@comment = Comment.find(params[:id])
@user = current_user
end
def update
@comment = Comment.find(params[:id])
@user = current_user
@comment.update(comment_params)
redirect_to @comment
end
def destroy
@user = current_user
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to comments_path
end
private
def comment_params
params.require(:comment).permit(:user_id, :location, :title, :body)
end
的意见,我试图给编辑的意见/删除这个样子的:
<% @user.comments.each do |w| %>
<tr>
<td>Location:<%= w.location %></td>
<td>Title:<%= w.title %></td>
<td>Body:<%= w.body %></td>
<td><%= link_to 'Edit', edit_comment_path %></td>
<td><%= link_to 'Destroy', comment_path,
method: :delete,
data: { confirm: 'Are you sure?' } %></td><br>
</tr>
<% end %>
感谢提供任何意见:-)
答
当您编辑/销毁您的评论时,您需要通过link_to
帮手中的实际评论。像link_to 'Destroy', w, method: :delete, data: { confirm: 'Are you sure?' }
会做的。
与编辑相似:link_to 'Edit', edit_comment_path(w)
是的!它的工作 - 但只有第二种方式,你的建议,括号中的w直接后面的路径:-) – Robert