在引用相同模型的事件记录中是否可能有 has 和 belongs to many 关系?
我想模拟 sibling 类型的关系。
class Child < ActiveRecord::Base
has_and_belongs_to_many :siblings
end
到目前为止,我已经创建了一个兄弟链接表:
class CreateSiblings < ActiveRecord::Migration
def change
create_table :siblings do |t|
t.integer :child1_id
t.integer :child2_id
t.timestamps
end
end
end
但我担心这会导致我编写难看的代码以获取实际实例:
siblings = []
child1.siblings.each do |s|
siblings << s.child2
end
我更希望能够通过以下方式获得一系列 child :
child1.siblings
我想知道我的链接表和模型关联应该如何支持这一点?
感觉我错过了一些非常明显的东西。
我使用的是 Rails 3.1。感谢您的帮助!
最佳答案
方法一:
我会简单地添加一个名为 parent_id
的列。
然后我会在模型上创建一个实例方法,例如:
def children
Model.where({ parent_id: id })
end
如果你想要 parent ,你可以这样做:
def parent
Model.where({ id: parent_id }).first
end
然后你可以像这样收集 sibling :
def siblings
parent.children.reject{ |r| r == self }
end
方法二:
您也可以尝试使用 belongs_to
关系,例如:
belongs_to :parent, class_name: "Model", foreign_key: :parent_id
但我对这种方法不是 100% 肯定。在它起作用之前,您可能需要稍微调整一下。
希望对你有帮助:)
\\埃米尔
关于ruby-on-rails - HABTM 与 self 的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498867/