I have the following relationships:
users -> user_roles <- roles
In my Role model, I created a habtm association with users:
I often find myself wanting to have a list of all the users that
aren’t associated with a given role so I thought that might be a good
candidate for a named association.
class Role
has_and_belongs_to_many :users, :join_table => ‘user_roles’
has_and_belongs_to_many :non_users, :class_name =>
‘User’, :join_table => ‘user_roles’, :finder_sql => ‘select * from
users where id NOT IN(select user_id from user_roles where role_id =
#{id})’
end
This sort of works, except non_users is cached. So if I update the
users associated with a role, then I have to explicitly call
r.non_users(true). I suppose I could create a callback in my model
that reloads the non_users every time the users collection is
updated. Does this seem like a bad idea? I’m hoping to get some
feedback.
I’ve also played with creating a standard non_users method in the
model, however making an association seems cleaner:
class Role
has_and_belongs_to_many :users, :join_table => ‘user_roles’
def non_users
User.find_by_sql(“select * from users where id NOT IN(select
user_id from user_roles where role_id = #{id})”)
end
end
Any suggestions people can provide would be great.
Thanks,
Steven