I got a really strange issue here. Here is the line causing all the trouble in my ability.rb
can [:edit, :update, :destroy], User, id: user.id
When I launch the rails console, I got the expected behaviour:
u = User.last
a = Ability.new(u)
a.can?(:edit, u)
=> true
a.can?(:edit, User.first)
=> false
However when I launch a web browser, log me in as a user and try to edit another one, CanCanCan remains silent. If I replace can
by cannot
, I can't edit any user. It's as if it didn't lookup the condition.
My UsersController
got this line on top
authorize_resource
I'm stuck with this, any help would be gladly appreciated.
cancancan 2.3.0
rails 5.2.1
Make sure that your instance ( @user
) is loaded before authorize_resource
action runs, otherwise it will check if user can access some Users ( can?(:edit, User)
, which is always true), instead of exact user.
before_action :load_user, except:[:index, :new, :create]
authorize_resource
...
private def load_user
@user = User.accessible_by(current_ability, action_name.to_sym).find(params[:id])
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.