# Employments example using Rich associations :through

**URL:** <https://www.ruby-forum.com/t/employments-example-using-rich-associations-through/133865>\
**Category:** Rails\
**Created:** [April 4, 2008, 2:46pm UTC](https://www.ruby-forum.com/t/employments-example-using-rich-associations-through/133865 "2008-04-04T14:46:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![macarthy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/71c47a/32.png) [@macarthy](https://www.ruby-forum.com/u/macarthy)\
**Post date:** [April 4, 2008, 2:46pm UTC](https://www.ruby-forum.com/t/employments-example-using-rich-associations-through/133865/1 "2008-04-04T14:46:52Z")

</div>

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|

???

---

<div class="post-metadata">

**Author:** ![macarthy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/71c47a/32.png) [@macarthy](https://www.ruby-forum.com/u/macarthy)\
**Post date:** [April 5, 2008, 5:05pm UTC](https://www.ruby-forum.com/t/employments-example-using-rich-associations-through/133865/2 "2008-04-05T17:05:02Z")

</div>

On Apr 4, 1:45 pm, macarthy [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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
