我有一个groups#new视图。登录current_user后,将允许他们创建一个组。

我的Groups#new视图:当前用户的隐藏字段工作正常,但是我需要将角色= 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 %>


然后在我的groups#create操作中:

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


显然,我有一个大规模分配问题。

最佳答案

您的成员资格模型没有groupleader的attr_accessible。这不能让我为什么它不起作用。

我也建议将其命名为group_leader_id

关于ruby-on-rails - Rails 3,如何在group#create Action 中设置user.role,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7787022/

10-12 14:16