[英]pass id out of model hash. Rails4 strong params
I am struggling with passing :project_id value into :comments model while having nested resources. 我在将资源嵌套的同时将:project_id值传递到:comments模型中很挣扎。 Hash that is passing from form looks like this:
从表单传递的哈希看起来像这样:
Parameters: {"utf8"=>"✓",
"comment"=>{"title"=>"sdfs", "desc"=>"ddf"},
"commit"=>"Create Comment",
"project_id"=>"1"}
And my permit attributes method as below: 我的许可属性方法如下:
params.require(:comment).permit(:title, :desc, :product_id)
I was also trying with code as such: 我也在尝试这样的代码:
#params.permit(:project_id, comments: [ :title, :desc])
#params.require(:project_id).permit(:project_id)
#params.require(:comment).permit(:title, :desc)
And my resources: 而我的资源:
resources :projects do
resources :comments
end
Problem is that :title and :desc are inserted but :project_id not... Could you tell me what I am doing wrong? 问题是:插入了:title和:desc,但没有插入:project_id ...您能告诉我我在做什么错吗? Thank you in advance!
先感谢您!
EDIT:// Form that I am using: EDIT://我正在使用的表格:
<%= form_for([@project, @comment]) do |f| %>
<% if @comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :desc %><br>
<%= f.text_field :desc %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Try this 尝试这个
params.permit(:project_id, comment: [ :title, :desc])
Note that its comment
and not comments
请注意,其
comment
而非comments
Wrong, maybe, in this sentence 这句话可能是错误的
params.require(:comment).permit(:title, :desc, :product_id)
Need :project_id 需要:project_id
You need to call #require
multiple times: 您需要多次致电
#require
:
params.require(:project_id)
params.require(:comment).permit(:title, :desc)
See: https://github.com/rails/strong_parameters#require-multiple-parameters 参见: https : //github.com/rails/strong_parameters#require-multiple-parameters
Alternatively, you could pass the project_id
via a hidden field in the form: 或者,您可以通过以下形式的隐藏字段传递
project_id
:
<%= f.hidden_field :project_id, value: @project.id %>
This would include the project_id
as a nested attribute in the comment
. 这将在
comment
包括project_id
作为嵌套属性。 Then you could use: 然后,您可以使用:
params.require(:comment).permit(:title, :desc, :project_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.