Hey list,
I was wondering on the definitive approach of setting attributes on
the join model of a has_many :through relation. After some googling, I
didn't find a "shortcut" approach to it, so I started tinkering, and
thinking.
Imagine users, groups, and memberships. Would something like this be a
good approach?
group.members << :user => @user , :role => Role.admin
If so, I could whip up a patch. If not, please enlighten me as to what
would be a good way to assign those properties.
cheers,
bartz
bphogan
(Brian P. Hogan)
April 14, 2009, 11:40pm
2
The generally accepted way of doig this is to start thinking of a
membership as a first_class entity.
When you 'sign up', for example, you are creating a membership.
Membership.create :user_id => params[:user_id], :group_id =>
params[:group_id], :joined_on => Date.today, :active => true
I have found that there is seldom a reason to take an extra DB hit to
grab one or both related objects. In fact, I'd argue that
@user = User.find_by_id(1)
@group = Group.find_by_id(1)
@group.members << @user
is a waste of objects and a waste of time. However, if you have both
objects already, simply assign them.
Membership.create :user => @user , :group => @group , :joined_on =>
Date.today, :active => true
Does that make sense?
The generally accepted way of doig this is to start thinking of a
membership as a first_class entity.
When you 'sign up', for example, you are creating a membership.
Membership.create :user_id => params[:user_id], :group_id =>
params[:group_id], :joined_on => Date.today, :active => true
I have found that there is seldom a reason to take an extra DB hit to
grab one or both related objects. In fact, I'd argue that
@user = User.find_by_id(1)
@group = Group.find_by_id(1)
@group.members << @user
is a waste of objects and a waste of time. However, if you have both
objects already, simply assign them.
Membership.create :user => @user , :group => @group , :joined_on =>
Date.today, :active => true
Does that make sense?
That does make sense, and I do agree :).
However, in a GroupsController.create, with a current_user, wouldn't
it be easy to do something like
def create
@group = Group.new(params[:group)
if @group.save && @group.users << current_user, :role => Role.admin
# etc
end
cheers,
bartz