【发布时间】:2016-09-13 16:42:28
【问题描述】:
在 Rails 中工作时,我正在合并 cocoon gem 以在我的食谱表单中动态生成成分字段。我可以使用accepts_nested_attributes_for 使其工作,但不能使用自定义嵌套属性编写器。例如,在合并 cocoon 之前,我的代码如下所示:
#recipe.rb
class Recipe
# name:string
has many :ingredients
# accepts_nested_attributes_for :ingredients
# the method below should do exactly the same thing as accepts_nested_attributes_for
def ingredients_attributes=(attributes)
attributes.each do |i, ingredient_hash|
self.ingredients.build(ingredient_hash)
end
end
end
#ingredient.rb
class Ingredient
# name:string, price:integer
belongs_to :recipe
end
#recipes_controller.rb (just the params part)
def recipe_params
params.require(:recipe).permit(:name, ingredients_attributes: [:name, :price])
end
为了使用茧宝石,我需要修改我的成分属性的强参数,并重构我的配方表单和配方模型,这是给我带来问题的最后一部分。我可以让它与这条线一起工作
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
但我想知道如何将选项合并到我的自定义属性编写器中。如果查看重构的控制器和表单代码会有所帮助,我也可以发布它。谢谢。
【问题讨论】:
-
我能问一下你为什么要这样做吗?如果你放入控制器而不是模型中,那就更麻烦了..
-
我不明白你的问题。我没有在控制器中放任何东西。在我的控制器中唯一改变的是强大的参数。其他所有内容都在
recipe.rb文件中 -
好吧,如果你从 rails 重写嵌套属性处理,一个好的起点是实际的 rails-code:github.com/rails/rails/blob/…
标签: ruby-on-rails nested-attributes cocoon-gem