Reputation: 45
I am trying to get a basic rails application running that helps capture the nutritional information of each food item from a list of food items. The nutritional information is stored per ingredient and calculated as the sum of individual ingredients.
Here is what I have so far:
Have two models Food and Ingredient. Each Food has many Ingredients and each Ingredient is used in many Food. The way I want to fix this is to break up the many-to-many with a table in between say Recipe which has the pk of Food and pk Ingredient. But my problem is that a Recipe can have many ingredients and an ingredient has many recipes. How do i split these two tables the best way so I can capture a food item and its list of ingredients? Or is there a better way to do the whole thing?
Say for the purposes of example Food has name, description and Ingredient has name, calories, nutrients.
Upvotes: 1
Views: 182
Reputation: 6100
You need has_many_through association.
You will organize like:
class Food < ActiveRecord::Base
has_many :recipes
has_many :ingredients,
through: :recipes
end
class Ingredient < ActiveRecord::Base
has_many :recipes
has_many :foods,
through: :recipes
end
class Recipe < ActiveRecord::Base
belongs_to :food
belongs_to :ingredient
end
This way, you can store additional info inside Recipe
Upvotes: 2