Rails: has_many with extra details?

喜欢而已 提交于 2019-12-04 19:41:12

Recipes and Ingredients have a has and belongs to many relationship, but you want to store additional information for link.

Essentially what you are looking for is a rich join model. But, a has_and_belongs_to_many relationship is not flexible enough to store the additional information you require. Instead you will need to use a has_many :through relatinship.

This is how I would set it up.

recipes columns: instructions

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

recipe_ingredients columns: recipe_id, ingredient_id, quantity

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

ingredient columns: name

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

This will provide a basic representation of what you're looking to do. You may want to add a validation to RecipeIngredients to ensure that each ingredient is listed once per recipe, and a callback to fold duplicates into one entry.

http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001888&name=has_and_belongs_to_many

http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001885&name=has_many

How about:

  1. class Ingredient (belongs to recipe, has many ingredientrecipecounts)
  2. class Recipe (has many ingredients, has many ingredientrecipecounts)
  3. class IngredientRecipeCount (belongs to ingredient, belongs to recipe)

This is not so much the Rails way as just establishing one more relation between the data in the database. It's not really a "has and belongs to many" because each ingredient only has one count per recipe, and each recipe one count per ingredient.. Which is the same count.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!