0

I'm trying to understand and implement Active Record Associations in Rails and am having some trouble understanding how to put together the specific relationships I need.

I have a Recipe model and an Ingredients model. Many Ingredients will belong to a single Recipe and therefore, a Recipe will have many Ingredients. I am having trouble grasping how this is handled through MySQL and how to implement these relationships in the models correctly. Here is the (relatively sparse) code I have, so far:

models/recipe.rb

class Recipe < ActiveRecord::Base
  has_many :ingredients
end

models/ingredient.rb

class Ingredient < ActiveRecord::Base
  has_and_belongs_to_many :recipes
end

However, I'm fairly certain the association line in ingredient.rb is incorrect.

How would I correctly implement these relationships?

Christian Benincasa
  • 1,215
  • 1
  • 21
  • 45

2 Answers2

1

Your Recipe model should have a has_and_belongs_to_many relationship with the ingredients instead of has_many. This allows a single recipe to have many ingredients (i.e. you can do @recipe.ingredients), while a single ingredient can be in many recipes (@ingredient.recipes).

It does seem kind of weird when first starting out, but once you've grokked how Rails relationships work, it becomes intuitive. You're on the right track.

x1a4
  • 19,417
  • 5
  • 40
  • 40
  • See this page for a concrete example: http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association – David Underwood May 28 '12 at 00:12
1

A has_many relationship implements a one to many mapping while has_and_belongs_to_many implements a many to many mapping. So a has_many is paired with a belongs_to while has_and_belongs_to_many are paired together.

The relationship between Recipe and Ingredients will be a many to many one if you also want to find out relations like which recipes a particular ingredient is being used in.

To implement a has_and_belongs_to_many in a mysql db you will have to create a third join table that maps all the links between the two tables.

You can look at this stackoverflow question to get a better idea of the format of the join table.

Community
  • 1
  • 1
Gaurav Shetty
  • 461
  • 4
  • 10