has_many :through default values
Posted
by David Lyod
on Stack Overflow
See other posts from Stack Overflow
or by David Lyod
Published on 2010-04-26T14:20:17Z
Indexed on
2010/04/26
14:23 UTC
Read the original article
Hit count: 155
ruby-on-rails
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.
© Stack Overflow or respective owner