HABTM与自我的关系?
问题描述:
在活动记录中引用同一模型是否有可能拥有并且属于许多关系?HABTM与自我的关系?
我想建模一个兄弟型的关系。
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
我宁愿能够通过写作得到一组儿童:
child1.siblings
我想知道我的链接表和模型关联应该如何支持这一点?
感觉就像我缺少一些非常明显的东西。
我在Rails 3.1上。谢谢你的帮助!
答
方法1:
我只想增加一个名为像parent_id
列。
然后,我会做一个实例方法的模型,是这样的:
def children
Model.where({ parent_id: id })
end
如果你愿意,你可以做这样的事情父:
def parent
Model.where({ id: parent_id }).first
end
然后你可以收集兄弟姐妹是这样的:
def siblings
parent.children.reject{ |r| r == self }
end
方法2:
您也可以尝试与belongs_to
关系,是这样的:
belongs_to :parent, class_name: "Model", foreign_key: :parent_id
但我不是百分之百肯定此方法。在它工作之前,您可能需要调整一下。
我希望它能帮助:)
\\周华健
据我看到的,兄弟姐妹总是喜欢parent.children减去实际的孩子,所以我乍一看,这额外的表似乎是不必要的开销。至少只要你不添加更多的功能或信息。当然你需要这个吗? – 2012-02-29 12:12:18
不幸的是,请参阅我对Ekampp的评论。在我的模型中,儿童有法定监护人,他们可能会这样做,但并不总是与他们的兄弟姐妹分享。 – Chris 2012-02-29 12:29:39