1
我用CanCan和rolify設置訪問權限的農場模型。慘慘/ Rolify:閱讀用戶對模型的訪問被拒絕
# 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: '[email protected]', password: 'password'
puts 'New user created: ' << user1.name
user2 = User.create! name: 'Second User', email: '[email protected]', password: 'password'
puts 'New user created: ' << user2.name
user9 = User.create! name: 'Default Admin', email: '[email protected]', 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沒有分配角色。
問題:爲什麼用戶2無法訪問ability.rb
中定義的所有農場?