4
我想創建一個食譜的軌道應用程序,但我很困惑如何創建視圖窗體和控制器邏輯。我有2種型號,配方和項目,參加在has_many :through
伴隨的成分模型如下:Rails與has_many複雜的視圖形式:通過協會
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上。