【问题标题】:Rails model for recipes and sub-recipes association食谱和子食谱关联的 Rails 模型
【发布时间】:2012-08-17 01:13:44
【问题描述】:

如何制作具有以下关联的项目表:

我的最终目标是能够创建包含许多组件和子食谱的食谱(我想将它们组合成一个下拉菜单)

Component

  belongs_to sub_recipe

End

Sub_recipe

  has_many components

  belongs_to recipe

End

Recipe 

  has_many subrecipes

  has_many components

End

【问题讨论】:

  • 这个问题没有任何意义。你能解释一下你想做什么吗?

标签: ruby-on-rails model associations


【解决方案1】:

每个项目都需要一个表格,关联表格需要一个表格

#class RawComponent < ActiveRecord::Base
#  has_and_belongs_to_many :recipes
#end

class Recipe < ActiveRecord::Base
  has_many :recipe_components
  has_many :subrecipes, :through => :recipe_components
  has_many :recipes, :through => :recipe_components
#  has_and_belongs_to_many :raw_components
end

class RecipeComponents < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :subrecipe, :class_name => :Recipe
end

假设你有一个@recipe,那么你可以去:

@recipe.subrecipes # find all subrecipes required to make this recipe
@recipe.recipes # find all recipes using this as a subrecipe

还添加了可能的 RawComponent 类,您可以将其用于不由其他组件组成的东西。但是你不需要它,如果你让每个 RawComponent 成为一个没有任何子配方的配方,这也是一种建模情况的有效方法。

关键点是关联模型 (RecipeComponents) 属于层次结构较高的 :recipe 和层次结构较低但与食谱具有相同类类型的 :subrecipe。

【讨论】:

  • 太棒了。你是最棒的 ronalchn!
  • ronalchn,当您说“您希望每个项目都有一个表”时,您的意思是我需要一个食谱表吗?如果是这样,我需要添加哪些列才能正确表示这些关联?
  • 我的意思是你需要两张桌子。一个用于存储项目,一个用于存储关联。
猜你喜欢
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2015-10-24
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2019-01-29
相关资源
最近更新 更多