Reputation: 22238
I have some accounts, and users, which are disjointed at the moment.
I need users to be able to be admins, or editors, or any (and many) accounts.
At the moment, I have this:
account.rb
has_many :memberships, :dependent => :destroy
has_many :administrators, :through => :memberships, :source => :user, :conditions => {'memberships.is_admin' => true}
has_many :editors, :through => :memberships, :source => :user, :conditions => {'memberships.is_editor' => true}
user.rb
has_many :memberships
has_many :accounts, :through => :memberships
has_many :editor_accounts, :through => :memberships, :source => :account, :conditions => {'memberships.is_editor' => true}
has_many :administrator_accounts, :through => :memberships, :source => :account, :conditions => {'memberships.is_admin' => true}
Essentially, what I am trying to acheive is a nice simple way of modelling this that works in a nice simple way. For instance, being able to do the following this would be really useful:
@account.administrators << current_user
current_user.adminstrator_accounts = [..]
etc
Upvotes: 0
Views: 206
Reputation: 211590
You should be able to do this, but it might be the notation you've used that interferes with the auto scope application:
has_many :memberships,
:dependent => :destroy
has_many :administrators,
:through => :memberships,
:source => :user,
:conditions => { :is_admin => true }
The conditions should be applied if and only if the condition keys match the column names on the association. So long as the users
table doesn't have a is_admin
column, this will be fine.
As a note, having multiple boolean flags for something like this can be awkward. Is it possible to be an admin and an editor? You may be better off with a simple role column and then use that:
has_many :administrators,
:through => :memberships,
:source => :user,
:conditions => { :role => 'admin' }
A multi-purpose column is often better than a multitude of single-purpose columns from an indexing perspective. You will have to index each and every one of these is_admin
type columns, and often you will need to do it for several keys. This can get messy in a hurry.
Upvotes: 1