rails cancan首次与roles_mask一起使用

时间:2011-04-29 02:06:38

标签: ruby-on-rails ruby-on-rails-3

首次使用带有roles_mask的cancan。继续在编辑视图中获取undefined method '&' for "1":String

form.html.erb

<% for role in User::ROLES %>
      <%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
      <%=h role.humanize %><br />
    <% end %>
    <%= hidden_field_tag "user[roles][]", "" %>
<% end %>

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable


  attr_accessible :email, :password, :password_confirmation, :remember_me, :firstname, :lastname, :username, :roles
    ROLES = %w[admin manager employee banned]

      def roles=(roles)
        self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
      end

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

      def role?(base_role)
        ROLES.index(base_role.to_s) <= ROLES.index(role)
      end

      def is?(role)
        roles.include?(role.to_s)
      end
end

1 个答案:

答案 0 :(得分:0)

你是否将roles_mask定义为“1”?角色访问者正在死亡,因为按位&amp;没有为字符串类定义运算符。您可能需要在您调用角色设置器的位置执行roles_mask_var.to_i。

伊恩。