Tuesday, May 19, 2009

has_many :through on the same model

1. I have 2 models person and secretary:

  • Person stores the details like, name, id, position, birthdate, etc
  • Secretary stores the mapping of person_id and secretary_id which are both foreign keys on person_id from person

class Person < ActiveRecord::Base
has_many :secretaries, :foreign_key => 'person_id'

has_one :assistant, :through => :secretaries, :conditions => [ on the attributes of secretary model]

...other details

end


class Secretary <>

belongs_to :person, :foreign_key => 'person_id'

belongs_to :assistant, :class_name => 'Person', :foreign_key => 'secretary_id'

. . . other details

end

2. Now I want to establish the association between Person to self as - A person would have a scretary who in turn is a person. Hence I have defined a new model assistant for the class Person and identified it in Secretary as -

belongs_to :assistant, :class_name => 'Person', :foreign_key => 'secretary_id'

3. Defining has_many :through / has_one :through - The most important to note here is to write - has_many :secretaries, :foreign_key => 'person_id'

and then

has_one :assistant, :through => :secretaries, :conditions => [ on the attributes of secretary model]

In my case has_one suffices since after the conditions only 1 active assistant would be returned. You cacn use has_many or has_one here.

4. Declare belongs_to :person, :foreign_key => 'person_id' in the Person model


And there you go !!! You are all set to enjoy the benefits of rails -Access the assistant as below -@person.assistant - Returns the assistant as a person object

@person.name - Person's name

@person.assistant.name - His asssitant's name
And a lot of fun ....

0 comments: