ruby-on-railsruby-on-rails-6cancancancancan

CanCan ability ignores a condition that should disallow access?


In ability.rb

can :edit, Physician, user_id: user.id

If my understanding is correct, this should look at the instance of physician in the controller, take its user_id attribute, and only allow access when it matches the current user id.

Instead, anyone can access anyone else's edit action! (bad)

What I think's happening

I have a custom route for the edit action:

get 'physicians/:physicianname/edit' => 'physicians#edit'

And in the edit controller:

@physician = Physician.find_by(physicianname: params[:physicianname])

Since I'm not looking up the physician in the usual way (using an :id), I think some of the cancan magic/defaults aren't applying as they should be.

But I cannot figure out why, or what I have to do to make it work.


Solution

  • i think you miss the check that should raise the unauthorized response. In your action, you should have something like this:

      @physician = Physician.find_by(physicianname: params[:physicianname])
      authorize! :edit, @physician
    

    Take a look at the gem wiki