首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails关联难题

Rails关联难题
EN

Stack Overflow用户
提问于 2013-02-27 10:46:00
回答 2查看 42关注 0票数 0

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

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

代码语言:javascript
复制
recipes
- name
- instructions

ingredients
- name

recipe_ingredients
- recipe_id
- ingredient_id
- preferred_ingredient_id
- amount

和关联:

代码语言:javascript
复制
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

我不确定如何处理preferred_ingredient_id和ingredient_id都指向相同的模型,而:preferred_ingredients实际上并不是一个符号。我需要以不同的方式设置我的关联吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-27 10:51:12

假设您将配料引用存储在RecipeIngredient中,

代码语言:javascript
复制
belongs_to :preferred_ingredient, class_name: 'Ingredient'

我还认为您引用的是RecipeIngredient中的成分,所以您也会希望将has_one更改为belongs_to。(如果食谱被删除,食材就被销毁了,这有意义吗?)

但考虑到你可能对某个特定的配料有很多选择,你可能会寻找更多这样的东西:

RecipeIngredient:

代码语言:javascript
复制
belongs_to :recipe
belongs_to :preferred_ingredient, class_name: 'Ingredient'
has_many :ingredient_options
has_many :ingredients, through: :ingredient_options

IngredientOption

代码语言:javascript
复制
belongs_to :recipe_ingredient
belongs_to :ingredient
票数 1
EN

Stack Overflow用户

发布于 2013-02-28 00:08:01

你也可以看看@ self-referential-association

这也可能会帮助你Rails Associations - has_many => :through - but same model

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15103295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档