CanCan / Rolify:模型上的用户读取权限被拒绝

时间:2013-01-04 13:10:06

标签: ruby-on-rails cancan accessible rolify

我使用CanCanrolify来设置Farm模型的访问权限。

# ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    # Create guest user aka. anonymous (not logged-in) when user is nil.
    user ||= User.new

    if user.has_role? :admin
      can :manage, :all
    else # guest user aka. anonymous
      can :read, :all
      # logged in user
      if user.has_role? :user
        can :create, Farm
        can :manage, Farm, :user_id => user.id
      end
    end
  end
end

我使用此处列出的一些测试数据为我的应用程序播种:

# seeds.rb
puts 'SETTING UP DEFAULT USER LOGIN'
user1 = User.create! name: 'First User', email: 'first.user@foo.com', password: 'password'
puts 'New user created: ' << user1.name
user2 = User.create! name: 'Second User', email: 'second.user@foo.com', password: 'password'
puts 'New user created: ' << user2.name
user9 = User.create! name: 'Default Admin', email: 'admin@foo.com', password: 'password'
puts 'New user created: ' << user9.name

puts 'ADDING SPECIAL ROLES TO USERS'
# No role for user1 here.
user2.add_role! :user
user2.save!
user9.add_role :admin
user9.save!

puts 'SETTING UP SOME FARMS'
farm1 = Farm.create! name: 'User1 farm', location: 'Mexico'
farm1.user = user1
farm1.save!
puts 'New farm created: ' << farm1.name
farm2 = Farm.create! name: 'User2 farm', location: 'Bolivia'
farm2.user = user2
farm2.save!
puts 'New farm created: ' << farm2.name
farm3 = Farm.create! name: 'Nobody\'s farm', location: 'Death Valley'
puts 'New farm created: ' << farm3.name

我在Rails控制台中运行以下命令,找出用户可以访问哪些服务器场(只读):

> Farm.accessible_by(Ability.new(User.find_by_name("First User"))).count
=> 3
> Farm.accessible_by(Ability.new(User.find_by_name("Second User"))).count
=> 1
> Farm.accessible_by(Ability.new(User.find_by_name("Default Admin"))).count
=> 3

请注意,user1没有分配角色。

问题:为什么user2无权访问ability.rb中定义的所有服务器场?

1 个答案:

答案 0 :(得分:0)

我必须学习用于定义能力重要事项顺序的艰难方式! documentation of CanCan揭示了每个人都要阅读的细节。简而言之:

  

通用规则首先遵循限制性规则。

以下是我提出的设置......

class Ability
  include CanCan::Ability

  def initialize(user)
    # Create guest user aka. anonymous (not logged-in) when user is nil.
    user ||= User.new

    if user.has_role? :admin
      can :manage, :all
    else
      # logged in user
      if user.has_role? :user
        can :manage, Farm, :user_id => user.id
        can :create, Farm
      end
       # guest user aka. anonymous
      can :read, :all
    end
  end
end