2011-07-12 71 views
1

我正在使用Ruby on Rails 3.0.9。我试图从关系表中获取所有父母的列表。这是代码。如何从关系表中获取所有父母的列表

require 'rubygems' 
gem 'activerecord', '3.0.9' 
require 'active_record' 

ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', 
             :database => ':memory:') 

ActiveRecord::Schema.define do 
    create_table :people, :force => true do |t| 
    end 
    create_table :relationships, :force => true do |t| 
    t.integer :parent_id 
    t.integer :child_id 
    end 
end 

class Person < ActiveRecord::Base 
end 

class Relationship < ActiveRecord::Base 
    belongs_to :parent, :class_name => 'Person' 
    belongs_to :child, :class_name => 'Person' 
end 

child = Person.create! 
parent = Person.create! 
Relationship.create!(:parent_id => parent.id, :child_id => child.id) 

# Person.parents_list needs to be implemented and 
# I am stuck and do not know how to get to that 
assert 1, Person.parents_list.size 
assert parent.id, Person.parents_list.first.id 
+0

所有常量都有父母方法。因此,我正在使用parents_list而不是父母。仅供参考。 –

回答

0

可以使用一种自我指涉的多对多的关系:

class Person < ActiveRecord::Base 
    has_many :relationships, 
      :foreign_key => 'child_id' 
    has_many :parents, 
      :through => :relationships, 
      :source => :child 

end 

child.parents.count # -> 1 

This blog entry有更多的细节。

编辑添加:啊,你只是想要每个人都是父母。您可以查询以下内容:

class Person < ActiveRecord::Base 
    has_many :parent_relationships, 
      :class_name => 'Relationship', 
      :foreign_key => 'parent_id' 
end 

Person.joins(:parent_relationships).count # -> 1 

通过加入关系表,您将只获得具有匹配关系(内部联接)的Person记录。这是covered by the excellent Rails guides.

+1

请注意,它不是我想要的child.parents。我正在寻找Person.parents_list。不过谢谢。 –

相关问题