# Looking for a simpler model using :through associations

**URL:** <https://www.ruby-forum.com/t/looking-for-a-simpler-model-using-through-associations/57642>\
**Category:** Rails\
**Created:** [April 12, 2006, 7:06pm UTC](https://www.ruby-forum.com/t/looking-for-a-simpler-model-using-through-associations/57642 "2006-04-12T19:06:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![morten](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/cdc98d/32.png) [@morten](https://www.ruby-forum.com/u/morten)\
**Post date:** [April 12, 2006, 7:06pm UTC](https://www.ruby-forum.com/t/looking-for-a-simpler-model-using-through-associations/57642/1 "2006-04-12T19:06:15Z")

</div>

Hi. I’m building a setup where I have users and groups, and a user can  
have an optional title in a group (eg. “owner”). I’m doing this using  
“has\_many :through” associations, using a Role model object as the join  
hub:

class User \< ActiveRecord::Base  
has\_many :roles, :dependent =\> :destroy  
has\_many :groups, :through =\> :roles  
end

class Group \< ActiveRecord::Base  
has\_many :roles, :dependent =\> :destroy  
has\_many :users, :through =\> :roles  
end

#The roles table has columns (id, user\_id, group\_id, title\_id)  
class Role \< ActiveRecord::Base  
:belongs\_to :user  
:belongs\_to :group  
:has\_one :title  
end

class Title \< ActiveRecord::Base  
:belongs\_to :role  
end

A typical use case is to find the owner of a given group, or more  
generally, find users with a given title in a given group. This can be  
done roughly like:

class Group \< ActiveRecord::Base  
has\_many :roles, :dependent =\> :destroy  
has\_many :users, :through =\> :roles

def find\_users\_in\_group\_with\_title(title)  
User.find\_by\_sql([  
"SELECT users.\* from users, roles, titles, groups "+  
"WHERE users.id = roles.user\_id "+  
"AND groups.id = roles.group\_id "+  
"AND titles.id = roles.title\_id "+  
"AND titles.name = ? "+  
“AND groups.id = ?”], title, self.id)  
end  
end

I find this (esp. the query) rather clumsy, as the core of the problem  
is simply “a user can have a role in a given group”. Has anyone come up  
with a more elegant model for expressing this?

Br,

Morten
