class Recipe < ApplicationRecord
has_many :recipe_components
has_many :components, through: :recipe_components
end
rails g model recipe:belongs_to component:belongs_to{polymorphic}
class RecipeComponent < ApplicationRecord
belongs_to :recipe
belongs_to :component, polymorphic: true
end
这将使您可以将食谱与配料、其他食谱或您喜欢的任何其他类别相关联。然而,当您将外键放在指向同一个表的表上时,它并不是真正的自引用关联。
这两个概念实际上是互斥的*,因为定义的自连接总是指向一个固定的表(本身)。碰巧两次引用同一个表的连接表不是自引用的。
# Not self-referential
class Friendship < ApplicationRecord
belongs_to :user, class_name: 'User'
belongs_to :other_user, class_name: 'User'
end
对于一个食谱,我还希望能够查看它是否用于任何其他食谱
一旦你想在树上走另一条路,事情就会开始变得疯狂:
class Recipe < ApplicationRecord
has_many :recipe_components_as_component,
class_name: 'RecipeComponent',
as: :component
has_many :recipies, through: :recipe_components_as_component
end
以及总成分是什么(即直接成分及其成分配方的所有成分)
这需要您使用递归“遍历树”并获取每个级别的所有关联项。一个巨大的问题本身,很可能会导致你后悔使用多态性。有several gems that tackle this problem。