Reputation: 6387
I have a Rails 6 app and am using CanCanCan to authorize resources.
For my plural resources CanCanCan has the load_and_authorize
method which looks in my abilities which resources the user has access to.
But know I want that a user can see its account.
In my user model I have
belongs_to :account
Where one account can have multiple users.
And in my abilities
can [:read], Account, id: user.account_id
So the user can access: /accounts/:id
But I would like him to access /account
instead.
So I created a singular resource resource :account
But how do i load the account resource now? I was hoping that CanCanCan does that for me. But it seems that ir does not. Is the only solution really to load the resource somehow with Account.find(id)
? This does not seem like a clean solution since the singular route routes to the plural controller where I have CanCanCan for authorizing.
Any ideas?
Upvotes: 1
Views: 200
Reputation: 1309
There are a couple of things here. First, your routes are entirely independent from your Cancancan resources (Cancancan deals with resources, not routes, even though some of the terminology is the same in both cases.) So, whatever routes you define, that's entirely different from the abilities you have defined for Cancancan.
The next step is to get your abilities set up properly so that your user can get at the right records. And it looks to me that your ability is correct: a user can read Account records when @account.id
matches @user.account_id
.
So, you should be able to use @user.account
and get back the associated Account record via the usual Rails association that you've set up. (I assume that Account has_many
Users, in the reciprocal of the belongs_to
association you've set for the User model.)
Upvotes: 0