I have a groups#new view. When the current_user is logged in, they are allowed to create a group.
My Groups#new view: the hidden field for the current user works fine, but I need to assign the role = groupleader to this current user.
<div>
<%= fields_for :membership do %>
<%= hidden_field_tag "user_id", current_user.id %>
<%= hidden_field_tag "role", "groupleader" %>
<% end %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Then in my groups#create action:
def create
@group = Group.new(params[:group])
@membership = current_user.memberships.build(:group_id => params[:group_id])
This is building a membership but not affecting the role.
My models are as follows:
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
accepts_nested_attributes_for :users
class User < ActiveRecord::Base #Built with Devise Gem
has_and_belongs_to_many :roles
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
—EDIT
Here is what I am playing with…. since I am sending a role parameter through the form,
@membership = current_user.memberships.build(:group_id => params[:group_id], :role => params[:role])
This is whats going through the log:
Parameters: {"group"=>{"title"=>"Test group w/leader", "description"=>"test"}, "commit"=>"Create Group", "role"=>"groupleader", "authenticity_token"=>"+GCK8bJddObwKdCoiqI5QzlGRyuci8b5JxmgXbOjgsc=", "utf8"=>"✓", "user_id"=>"8"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 LIMIT 1
WARNING: Can't mass-assign protected attributes: role
Obviously, I have a mass-assign issue.
Your membership model doesn’t have attr_accessible for groupleader. Can’t this me the reason why is it not working.
Also I suggest naming it as group_leader_id