Employments example using Rich associations :through

What is the best way to deal with this model in rails 2.0 +

class School < ActiveRecord::Base

school model has a name attribute

has_many :employments
has_many :teachers , :through=> :employments
end

class Teacher < ActiveRecord::Base

teacher model has a name attribute

has_many :employments
has_many :schools , :through=> :employments

end

class Employment < ActiveRecord::Base

employment has a start_date and an end_date

end_date is null if the teacher is currently employed

by that school

belongs_to :school
belongs_to :teacher
end

What is the best way to code this, so that I can do the following :

teacher.schools.current.name

teacher.schools.past[0].name
teacher.schools.past[0].start_date
teacher.schools.past[0].end_date

school.teachers.current[0].name
school.teachers.current[0].start_date

school.teachers.past[0].name

Thanks

Something like :

user.favorite_articles.each do |fav|

???

On Apr 4, 1:45 pm, macarthy [email protected] wrote:

has_many :employments
belongs_to :teacher
end

What is the best way to code this, so that I can do the following :

You can do this with association proxies, so for teachers, something
like

has_many :schools, :through => :employments do
def current
find :first, :conditions => ‘end_date IS NULL’
end
def past
find :all, :conditions => ‘end_date is NOT NULL’
end
end

would probably do the trick (just typed in my mail client, so you may
have to do some fiddling to get this to work.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs