Rails:CanCan每个用户的许多角色都无法保存复选框值

时间:2016-12-08 07:15:50

标签: ruby-on-rails cancan

我正在关注CanCan维基以获得我的授权。 https://github.com/ryanb/cancan/wiki/Role-Based-Authorization

维基说,我做了每一步。 我无法保存值字段'角色'以及' roles_mask',每次提交表格时,他们都是零。任何人都可以告诉我如何解决它?

用户架构

  create_table "users", force: :cascade do |t|
    t.string   "username",       
    t.string   "password_digest",
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "role"
    t.integer  "roles_mask"
  end

用户控制器

class UsersController < ApplicationController
  def new
    @user = OmsUser.new
  end

  def create
    @user = User.new(user_params)
    if @saved = @user.save
      flash[:success] = "Success"
    end
  end

  private

  def user_params
    params.require(:user).permit(:username, :password, :password_confirmation,:role, :roles_mask)
  end
end

_form.html.erb

<%= form_for @user do |f| %>
  <%= f.text_field :username %>
  <%= f.password_field :password %>
  <%= f.password_field :password_confirmation %>
  <% for role in User::ROLES %>
    <%= check_box_tag "user[roles][#{role}]", role, @user.roles.include?(role), {:name => "user[roles][]"}%>
    <%= label_tag "user_roles_#{role}", role.humanize %><br />
  <% end %>
  <%= hidden_field_tag "user[roles][]", "" %>
  <%= f.submit %>
<%end%>

User.rb

class User < ApplicationRecord
  ROLES = %w[admin user manager]

  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
  end

  def roles
    ROLES.reject do |r|
      ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
    end
  end
end

1 个答案:

答案 0 :(得分:1)

user_params您未允许roles

params.require(:user).permit(:username, :password, :password_confirmation, roles: [])

在您的user模型中,您添加了以下方法:

# in models/user.rb
def roles=(roles)
  self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end

def roles
  ROLES.reject do |r|
    ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
  end
end

这些也是保存角色所必需的。