質問

I use CanCan and rolify to setup access rights for a Farm model.

# 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

I seed my application with some test data listed here:

# 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

I run the following command in Rails console to find out which farms can be accessed (read-only) by a user:

> 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

Please note that user1 does not have a role assigned.

Question: Why does user2 not have access to all the farms as defined in ability.rb?

役に立ちましたか?

解決

I had to learn the hard way that the order in which you define abilities matters! The documentation of CanCan reveals the details for everybody to read through. In short:

Generic rules go first, restrictive rules follow.

Here are the settings I came up with ...

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top