Forum: Ruby on Rails Looking for a simpler model using :through associations

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Morten (Guest)
on 2006-04-12 21:06
(Received via mailing list)
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

class User < ActiveRecord::Base
   has_many    :roles, :dependent => :destroy
   has_many    :groups, :through => :roles

class Group < ActiveRecord::Base
   has_many :roles, :dependent => :destroy
   has_many :users, :through => :roles

#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

class Title < ActiveRecord::Base
   :belongs_to :role

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)
	"SELECT users.* from users, roles, titles, groups "+
	"WHERE  = roles.user_id "+
	"AND = roles.group_id "+
	"AND = roles.title_id "+
	"AND = ? "+
	"AND   = ?"], title,

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?


This topic is locked and can not be replied to.