Railsで作業しています。私はレシピフォームに原料フィールドを動的に生成するためにコクーンの宝石を取り入れています。 を使用して動作させることはできますが、カスタムネストされた属性ライターは使用できません。例えば、繭を組み込む前に、私のコードは次のように見えた:繭の宝石を使用するためにはRailsのカスタムネストされた属性ライターにallow_destroyオプションを組み込む方法
#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
、私はingredients_attributesのための私の強いのparamsを変更して、私のレシピフォームおよびレシピモデルをリファクタリングする必要があり、それはです私に問題を与えている最後の部分。私はそれがライン
accepts_nested_attributes_for :ingredients, reject_if: :all_blank, allow_destroy: true
で動作させることができますが、私は代わりに私のカスタム属性ライターにオプションを組み込む方法を知っていただきたいと思います。リファクタリングされたコントローラとフォームコードを確認すると便利ですが、投稿することもできます。ありがとう。
Canなぜあなたはそれをしたいのですか?あなたがモデルではなくコントローラに入れば、それはずっと面倒です。 – luissimo
私はあなたの質問を理解していません。私はコントローラーに何も入れていません。コントローラーで変更されるのは強力なパラメーターだけです。他のすべては 'recipe.rb'ファイルにあります – TDB
railsからネストされた属性の扱いを書き直す場合は、実際のレールコードが良いでしょう:https://github.com/rails/rails/blob/ 0fe76197d2622674e1796a9a000995a7a1f6622b/activerecord/lib/active_record/nested_attributes.rb#L319 – nathanvda