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?
Your
Recipemodel should have ahas_and_belongs_to_manyrelationship with the ingredients instead ofhas_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.