How to to get the list of all parents from relationships table
I am using Ruby on Rails 3.0.9. I am trying to get the list of all the parents from the relationships table. Here is code.
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 :r开发者_如何学Goelationships, :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
You can use a self-referential many to many relationship:
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 has more details.
Edited to add: Ah, you just want every Person who is a parent. You can query for that:
class Person < ActiveRecord::Base
has_many :parent_relationships,
:class_name => 'Relationship',
:foreign_key => 'parent_id'
end
Person.joins(:parent_relationships).count # -> 1
By joining against the Relationships table you'll get only the Person records with matching Relationships (an inner join). This is covered by the excellent Rails guides.
精彩评论