I'm trying to create a rails app for recipes, but am confused on how to create the view forms and controller logic. I have 2 models, Recipe and Item, joined in a has_many :through
association with an Ingredient model as follows:
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? 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.
The accepts_nested_attributes_for
-method is what you are looking for.
Ryan Bates has done an excellent Railscast on it.
You should also check the documentation for Active Record Nested Attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With