我正在努力将传递:project_id值转换为:注释模型,同时拥有嵌套资源。从表单传递的哈希看起来像这样:
Parameters: {"utf8"=>"✓",
"comment"=>{"title"=>"sdfs", "desc"=>"ddf"},
"commit"=>"Create Comment",
"project_id"=>"1"}
我的许可属性方法如下:
params.require(:comment).permit(:title, :desc, :product_id)
我也在尝试使用代码:
#params.permit(:project_id, comments: [ :title, :desc])
#params.require(:project_id).permit(:project_id)
#params.require(:comment).permit(:title, :desc)
我的资源:
resources :projects do
resources :comments
end
问题是:插入了title和:desc但是:project_id没有...你能告诉我我做错了什么吗?提前谢谢!
编辑:// 我正在使用的表格:
<%= 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 %>
答案 0 :(得分:2)
试试这个
params.permit(:project_id, comment: [ :title, :desc])
请注意其comment
而非comments
答案 1 :(得分:0)
错误,也许,在这句话中
params.require(:comment).permit(:title, :desc, :product_id)
需要:project_id
答案 2 :(得分:0)
您需要多次致电#require
:
params.require(:project_id)
params.require(:comment).permit(:title, :desc)
请参阅:https://github.com/rails/strong_parameters#require-multiple-parameters
或者,您可以通过表单中的隐藏字段传递project_id
:
<%= f.hidden_field :project_id, value: @project.id %>
这将project_id
作为comment
中的嵌套属性。然后你可以使用:
params.require(:comment).permit(:title, :desc, :project_id)