这与我的另一个问题相符;当我提交属于特定帖子的新评论时,尝试获取正确的post_id。
_form.html.erb
<%= f.hidden_field :project_id, :value => params[:id] %>
<%= f.hidden_field :post_id, :value => params[:id].post_id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
答案 0 :(得分:5)
@post = Post.find(params[:id])
进行了设置
# this is not needed, on the create, get it from the post?
<%= f.hidden_field :project_id, :value => params[:id] %>
# if you do want to pass it, guessing something like this
<%= f.hidden_field :project_id, :value => @post.project_id %>
# pass the post id to the create action
<%= f.hidden_field :post_id, :value => @post.id %>
# if the comment has a project_id
# @comment.project = @post.project ?
# do not send this in hidden field, get the value in your controller
# otherwise the user can change this value to another user when submitting the form
<%= f.hidden_field :user_id, :value => current_user.id %>
您可能还想考虑在评论的情况下使用嵌套路线吗?
我建议您阅读rails指南中的视图助手: http://guides.rubyonrails.org/index.html
http://guides.rubyonrails.org/getting_started.html页面实际上包含带评论的帖子的代码示例
答案 1 :(得分:0)
问题的解决方案是简单地将from从部分放回到实际的视图文件中,然后使用
<%= f.hidden_field :post_id, :value => params[:id].post_id %>
然而,正如house9指出的那样;使用隐藏字段传递表单中的值是一个巨大的安全漏洞。所以改变它。