Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 542
paniwani Avatar asked Dec 27 '22 09:12

paniwani


1 Answers

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

like image 120
klaffenboeck Avatar answered Jan 14 '23 03:01

klaffenboeck