# Sync :through association

**URL:** <https://www.ruby-forum.com/t/sync-through-association/117991>\
**Category:** Rails\
**Created:** [October 23, 2007, 1:54am UTC](https://www.ruby-forum.com/t/sync-through-association/117991 "2007-10-23T01:54:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![sp00nyg](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/edb3f5/32.png) [@sp00nyg](https://www.ruby-forum.com/u/sp00nyg)\
**Post date:** [October 23, 2007, 1:54am UTC](https://www.ruby-forum.com/t/sync-through-association/117991/1 "2007-10-23T01:54:56Z")

</div>

I have a User class that is associated with Contact through  
UserContact.

class User  
has\_many :user\_contacts  
has\_many :contacts, :through =\> :user\_contacts, :source  
=\> :contact, :order =\> ‘contacts.last\_name ASC’  
end

UserContact defines a many-to-many relationship with attributes. The  
problem I have is how to best access the attributes in UserContact  
without constantly accessing the database. For example:

contacts = user.contacts  
contacts.each do |contact|

# Do stuff with contact

# How do I access the UserContact instance that through used to

access the contact?  
end

I could do

uc = user.user\_contacts.find\_by\_contact\_id(contact.id)

but that results in another database call for each contact.

I suppose I could do something like:  
user\_contacts = user.user\_contacts.find(:all, :include  
=\> :contact, :order =\> ‘contacts.last\_name ASC’)  
user\_contacts.each do |uc|  
puts uc.contact.last\_name  
puts uc.attribute\_name  
end

I was hoping there might be another way to work :through backwards  
from the target. The above will work, but it is not as clean as  
the :through relationship.
