CanCanCan permissions for has_and_belongs_to_many association

cancan, relationship, ruby-on-rails

Solution

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)

Problem

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?

Original source