ActiveRecord associations, has_many_through

I've been trying to wrap my head around these associations and I've run into a bit of a snag. The app I'm working on has 2 models at the moment: Ingredient, and Recipe. The logic behind each is as follows:

The Ingredient model contains info on food items, such as name, bulk price, etc. The Recipe model contains the name of the recipe, preparation instruction, and a list of ingredients (along with the amount required for the recipe).

After digging through some of the questions on here, and watching a few railscasts I've determined that a has_many_through relationship may be better for what I'm attempting to do, since I'd like to include additional info about the ingredient in the recipe (amount required).

Based on my limited experience in this area, I'd like to approach it like this:

class Recipe < ActiveRecord::Base
  has_many :ingredients_recipes
  has_many :ingredients, :through => :ingredients_recipes
end

class Ingredient_Recipe < ActiveRecord::Base
  belongs_to :ingredient
  belongs_to :recipe
end

class Ingredient < ActiveRecord::Base
  has_many :ingredients_recipes
  has_many :recipes, :through => :ingredients_recipes
end

Where the ingredients_recipes table would have fields similar to this: recipe_id, ingredient_id, ingredient_qty (for storing how much of a particular ingredient is in a recipe)

Is this the proper way to approach it code-wise, based on the functionality I mentioned above? Any help would be greatly appreciated. Thanks!

Edit I'd also like to be able to add these new ingredients to the recipe from the recipe form. Would this require anything extra, like having to do accepts_nested_attributes_for the through table, or is this something that Rails would handle on it's own?

Answers


The :has_many through approach works best when one object can have zero or many other objects connected & there are some properties associated with each connection.

For example, in your case, you'd be storing the amount of each ingredient along with the recipe_id an ingredient_id in the Connections table.

So, it looks GOOD to me. :)

However, you should consider naming your Ingredient_Recipe table to something more appropriate.


Need Your Help

ActionScript 3 - Using Associative Array to count occurrences

actionscript-3 hash associative-array idioms

Hey everyone, in many programming languages there is this great idiom that lets you use a hash to count occurrences of items. Eg in Perl, suppose you have a list of students and you want to see how...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.