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上。

回答