简体   繁体   English

Rails复杂视图表单与has_many:通过关联

[英]Rails complex view form with has_many :through association

I'm trying to create a rails app for recipes, but am confused on how to create the view forms and controller logic. 我正在尝试为食谱创建一个rails应用程序,但我对如何创建视图表单和控制器逻辑感到困惑。 I have 2 models, Recipe and Item, joined in a has_many :through association with an Ingredient model as follows: 我有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

This association works in the console. 此关联在控制台中有效。 For example: 例如:

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"]

However, I don't understand how to create the new recipe view so that I can add ingredients directly to a recipe in one page. 但是,我不明白如何创建新的配方视图,以便我可以在一个页面中将配料直接添加到配方中。 Do I need to use fields_for or nested attributes? 我是否需要使用fields_for或嵌套属性? How do I build the view form and controller logic to create a recipe, with ingredients, in one page? 如何构建视图表单和控制器逻辑以在一个页面中创建具有成分的配方?

I'm on Rails 3.1.3. 我在Rails 3.1.3上。

The accepts_nested_attributes_for -method is what you are looking for. accepts_nested_attributes_for -method就是你要找的东西。 Ryan Bates has done an excellent Railscast on it. Ryan Bates在它上面做了很好的Railscast

You should also check the documentation for Active Record Nested Attributes 您还应该查看Active Record Nested Attributes文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM