Ruby on rails 铁路协会难题

Ruby on rails 铁路协会难题,ruby-on-rails,activerecord,associations,Ruby On Rails,Activerecord,Associations,我正在创建一个存储食品配方的服务,我正在尝试创建一个成分列表,每个成分都有可选的首选品牌。例如,我可能会说,意大利面配方使用去皮西红柿,首选品牌是Cento。我的配料存储在层次分类树中,因此首选配料是该树中配料的子级 以下是我的简化数据库设置: recipes - name - instructions ingredients - name recipe_ingredients - recipe_id - ingredient_id - preferred_ingredient_id - a

我正在创建一个存储食品配方的服务,我正在尝试创建一个成分列表,每个成分都有可选的首选品牌。例如,我可能会说,意大利面配方使用去皮西红柿,首选品牌是Cento。我的配料存储在层次分类树中,因此首选配料是该树中配料的子级

以下是我的简化数据库设置:

recipes
- name
- instructions

ingredients
- name

recipe_ingredients
- recipe_id
- ingredient_id
- preferred_ingredient_id
- amount
各协会:

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

class Ingredient < ActiveRecord::Base
end

class RecipeIngredient < ActiveRecord::Base
  belongs_to :recipe
  has_one :ingredient
  has_one :preferred_ingredient
end
类配方:recipe\u配料
有很多:首选成分,:至=>:配方成分
结束
类组件

我不确定如何处理首选配料id和配料id都指向同一个模型,并且:首选配料实际上并不作为符号存在。我是否需要以不同的方式设置关联?

假设您正在RecipeCredit中存储成分引用

belongs_to :preferred_ingredient, class_name: 'Ingredient'
我还认为您在引用RecipeCredit中的成分,因此您希望将
has\u one
也更改为
所属。(如果配方被删除,成分被销毁是否有意义?)

但考虑到你可能对某一特定成分有很多选择,你可能会寻找类似的东西:

接受方:

belongs_to :recipe
belongs_to :preferred_ingredient, class_name: 'Ingredient'
has_many :ingredient_options
has_many :ingredients, through: :ingredient_options
预测

belongs_to :recipe_ingredient
belongs_to :ingredient

你也可以看看@

这也可能对你有所帮助

model\u name
是属于关联的未知键
属于:首选成分,类别名称:“成分”
应该替换,这样才有意义。谢谢你的帮助!