I have a model Group and model User
They are connected both directions with “has_many :through => groups_users”
groups_users table has an attribute, called moderator, specifying whether a user is a moderator of the group
when i am trying to update join module attribute, i get a mistake
way i am doing it now:
@group_membership=@group.groups_users.find_by_user_id(@user.id)
if @group_membership!=nil
@group_membership.moderator=true
else
@group_membership=GroupsUser.new(:user_id => @user.id, :group_id => @group.id, :moderator => true)
end
@group_membership.save
Code is producing mysql mistake:
Unknown column 'id' in 'where clause': UPDATE `groups_users` SET `moderator` = 1 WHERE `id` = NULL
Is there nicer way to do that or should i add id column to the groups_users join model table and index it on id?
Yes, you should create an
idcolumn on the groups_users table.Since you are using
has_many :throughthe join table should have anidcolumn on it (which is an auto-incrementing primary key). This is because every Rails model needs an id column and the join table has its own model (GroupsUser). BTW, you may want to rename to something like Membership).The other type of many-to-many association is
has_and_belongs_to_many. I’m assuming you migrated from this because that does not use anidcolumn on the join table. For more information about these two associations, check out my Railscasts episode on this topic.