Complex Rails submission form with has_many: through union

I am trying to create a rails application for recipes, but I donโ€™t understand how to create presentation forms and controller logic. I have 2 models, a recipe and an element, combined into a has_many :through association with the 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 link works in the console. For instance:

 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 a new presentation of the recipe so that I can add the ingredients directly to the recipe on one page. Do I need to use fields_for or nested attributes? How to create a presentation form and controller logic to create a recipe with ingredients on one page?

I'm on Rails 3.1.3.

+4
source share
1 answer

The accepts_nested_attributes_for method is what you are looking for. Ryan Bates made an excellent Railscast on it.

You should also check the documentation for nested Active Record attributes.

+11
source

Source: https://habr.com/ru/post/1386608/


All Articles