1
我有一個groups#new
視圖。當current_user登錄時,它們被允許創建一個組。rails 3,如何在一個組中設置user.role#創建動作
我的羣組#新視圖:當前用戶的隱藏字段工作正常,但我需要將role = groupleader分配給當前用戶。
<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 %>
然後在我的組#創建行動:
def create
@group = Group.new(params[:group])
@membership = current_user.memberships.build(:group_id => params[:group_id])
這是建設一個成員,但不影響作用。
我的型號如下:
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
---編輯 以下是我與玩....因爲我通過表單發送的角色參數,
@membership = current_user.memberships.build(:group_id => params[:group_id], :role => params[:role])
這是通過日誌打算什麼:
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
很顯然,我有一個大規模分配ISSU即
成員模型只是處理組和用戶/角色之間的關係。我可以通過attr_accessible使角色字段可用...我會玩這個。我如何將它命名爲group_leader_id? groupleader只是一個角色的名字。 –