【问题标题】:Strong parameters for nested attributes with nested attributes?具有嵌套属性的嵌套属性的强参数?
【发布时间】:2016-04-15 00:56:38
【问题描述】:

我有一个“食谱”,其中有_many“Ilists”和“Ilist”有_one“成分”,我试图以一种形式提交所有内容,但我遇到了强参数的问题。我可以提交表单,但查看我可以在 POST 请求中看到的控制台:

"Unpermitted parameter: ingredient_attributes"

recipes_controller.rb

class RecipesController < ApplicationController
 before_action :set_recipe, only: [:show, :edit, :update, :destroy]

def index
  @recipes = Recipe.all
end
def create
  @recipe = Recipe.new
  6.times { @recipe.ilists.build }
end
. 
.
private
  def recipe_params
    params.require(:recipe).permit(:title, :photo, ... , :description, :calories, ilists_attributes: [ :ingredient_attributes, :quantity])
  end
end

我试过这样写,但它不起作用:

, ilists_attributes: [ ingredient_attributes: [ name, calories, ... ], :quantity])

请帮助这正在杀死我!

这是我提交的表单

 <%= f.fields_for :ilists do |builder| %>
  <tr>

  <%= builder.fields_for :ingredient, Ingredient.new do |b| %>
    <td><%= b.collection_select(:_id, Ingredient.all, :id, :name) %></td>
  <% end %>

  <td><%= builder.text_field :quantity %></td>

  </tr>

【问题讨论】:

  • 您的 POST 参数是什么样的,以及为成分选择标签生成的 html 是什么?它们是否符合预期?

标签: ruby-on-rails mongoid strong-parameters


【解决方案1】:

你已经接近了。这里只需要遵循几条规则。

这是正确的强参数声明

def recipe_params
  params.require(:recipe).permit(:name , ilists_attributes:  [ :quantity, ingredients_attributes: [ :name, :calories ]])
end
  1. 确保将复数对象复数(在您的情况下,它应该是成分属性而不是成分)
  2. 确保将单个属性放在嵌套的属性数组之前(在您的情况下,将 quantity 移到列表的前面,放在成分属性之前)
  3. 确保属性后面有颜色:

【讨论】:

  • 不在“has_one”关联的“ingredient_attributes”中?
  • 确实如此。并不是说那部分是错误的,只是你必须注意复数形式:)
  • 我对 Rails 还很陌生,我学到了很多东西:P
【解决方案2】:

我在其他地方找到了解决方案,我所要做的就是将成分属性交换到另一边。

, ilists_attributes: [ :quantity, ingredient_attributes: [ name, calories, ... ] ])

【讨论】:

    猜你喜欢
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多