![](/img/trans.png)
[英]Rails: Class inheritance and complex polymorphic has_many :through association
[英]Rails complex view form with has_many :through association
我正在嘗試為食譜創建一個rails應用程序,但我對如何創建視圖表單和控制器邏輯感到困惑。 我有2個模型,配方和項目,加入了has_many :through
與Ingredient模型的關聯,如下所示:
class Recipe < ActiveRecord::Base
has_many :ingredients
has_many :items, :through => :ingredients
end
class Item < ActiveRecord::Base
has_many :ingredients
has_many :recipes, :through => :ingredients
end
class Ingredient < ActiveRecord::Base
# Has extra attribute :quantity
belongs_to :recipe
belongs_to :item
end
此關聯在控制台中有效。 例如:
Recipe.create( :name => 'Quick Salmon' )
Item.create( :name => 'salmon', :unit => 'cups' )
Ingredient.create( :recipe_id => 1, :item_id => 1, :quantity => 3)
Recipe.first.ingredients
=> [#<Ingredient id: 1, recipe_id: 1, item_id: 1, quantity: 3]
Recipe.first.items
=> [#<Item id: 1, name: "salmon", unit: "cups"]
但是,我不明白如何創建新的配方視圖,以便我可以在一個頁面中將配料直接添加到配方中。 我是否需要使用fields_for
或嵌套屬性? 如何構建視圖表單和控制器邏輯以在一個頁面中創建具有成分的配方?
我在Rails 3.1.3上。
accepts_nested_attributes_for
-method就是你要找的東西。 Ryan Bates在它上面做了很好的Railscast 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.