如何从关系表中获取所有父项的列表

时间:2011-07-12 16:30:49

标签: ruby-on-rails

我正在使用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

1 个答案:

答案 0 :(得分: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

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