Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CanCanCan permissions for has_and_belongs_to_many association

I have has_and_belongs_to_many association between User and Client. Table clients_users has got indexes for User and Client. My models are:

class User < ActiveRecord::Base
  rolify
  has_and_belongs_to_many :clients
end

class Client < ActiveRecord::Base
  resourcify
  has_and_belongs_to_many :users
end

My controllers are:

class Admin::ClientsController < ApplicationController
  load_and_authorize_resource
end

class Admin::UsersController < ApplicationController
  load_and_authorize_resource
end

I need something like this in my ability.rb

user ||= User.new # guest user (not logged in)

can :read, :all
can :manage, Client, :clients_users => { :user_id => user.id }

So I could manage client only when in clients_users table is a record with user_id and id of this client. How do I make it work?

like image 763
yazoou Avatar asked Oct 19 '25 01:10

yazoou


1 Answers

when you use has_and_belongs_to_many then you don't have access to the join model, simply because there's no join model, if you want to access that then you need to do has_many :through instead.

But in your case you don't really need to access the join model, because Client has a users attribute, and User has a clients attribute, so why not just use that instead:

I think something like this should work

can :manage, Client, id: user.clients.pluck(:id)
like image 50
Mohammad AbuShady Avatar answered Oct 21 '25 17:10

Mohammad AbuShady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!