has_many :through default values
- by David Lyod
I have a need to design a system to track users memberships to groups with varying roles (currently three).
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
class Role < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :role
belongs_to :group
end
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
end
Ideally what I want is to simply set
@group.users << @user
and have the membership have the correct role. I can use :conditions to select data that has been manually inserted as such :
:conditions => ["memberships.grouprole_id= ? ", Grouprole.find_by_name('user')]
But when creating the membership to the group the grouprole_id is not being set.
Is there a way to do this as at present I have a somewhat repetitive piece of code for each user role in my Group model.