我想设置roles_mask
整数列来设置user
的角色。
这是我的用户模型:
class User < ActiveRecord::Base
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
has_and_belongs_to_many :colleges
has_and_belongs_to_many :groups
has_and_belongs_to_many :pages
has_and_belongs_to_many :partners
ROLES = %w[admin college department news page ostad]
def roles=(roles)
roles = [*roles].map { |r| r.to_sym }
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
scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0 "} }
def role_symboles
roles.map(&:to_sym)
end
def has_role?(role)
roles.include?(role)
end
end
我的用户控制器中有user_params
:
def user_params
params.require(:user).permit(:name, :username, :roles, :email, :password, :password_confirmation, {:college_ids => [], :group_ids => [], :page_ids => [], :partner_ids => []})
end
这是我的表格:
<%= form_for(@user) do |f| %>
....
<div class="row">
<div class="large-2 medium-2 small-12 columns">
<%= f.label t("admin.user.role") , class: "inline" %>
</div>
<div class="large-10 medium-10 small-12 columns">
<% for role in User::ROLES %>
<span style="width:40px">
<%= check_box_tag "user[roles][#{role}]", role, @user.roles.include?(role), {:name => "user[roles][]"}%>
<%= label_tag "user_roles_#{role}", role.to_s.humanize %>
</span>
<% end %>
<%= hidden_field_tag "user[roles][]", nil %>
</div>
</div>
<% end %>
我的用户模型中有roles_mask
列。
但是当我创建用户并设置所有列时,roles_mask
列仍为null
。