在隐藏字段中传递帖子ID的值

Jam*_*s F 3 ruby ruby-on-rails ruby-on-rails-3

这与我的另一个问题相符; 当我提交属于特定帖子的新评论时,尝试获取正确的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 %>
Run Code Online (Sandbox Code Playgroud)

hou*_*se9 5

有点很难确切地知道你在做什么而没有看到更多的代码,但我的猜测是@post实例变量已@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 %>
Run Code Online (Sandbox Code Playgroud)

您可能还想考虑在评论的情况下使用嵌套路线?

我建议您阅读rails指南中的视图助手:http: //guides.rubyonrails.org/index.html

http://guides.rubyonrails.org/getting_started.html页面实际上有代码示例使用注释后