1

我使用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

4

1 回答 1

0

我必须努力学习你定义能力的顺序很重要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
于 2013-01-18T17:09:49.807 回答