CanCan and ActiveRecord associations

172 Views Asked by At

I have the following line in my Ability.rb

can :index, :calls, :store => { area_id: user.area_id }

In calls_controller.rb

load_and_authorize_resource :store
load_and_authorize_resource :call, :through => :store

def index
    @calls = Call.accessible_by(current_ability, :index)
end

In the model call.rb

belongs_to :store

Yet when I try to access @calls in a view I get the following SQL error

Mysql::Error: Unknown column 'store.area_id' in 'where clause': SELECT  `calls`.* FROM `calls` INNER JOIN `stores` ON `stores`.`id` = `calls`.`store_id` WHERE `store`.`area_id` = 4 LIMIT 20 OFFSET 0

This is because the SQL query should have "WHERE stores.area_id = 4". Is this a problem with CanCan or do I have something setup wrong? I'm using CanCan 2.0, FYI.

2

There are 2 best solutions below

0
On

If you limit the stores a user can see

  if !user.area_id.nil? and user.area_id != 0 then
    user_stores = Store.where(:area_id => user.area_id)
  end

Then you can pass an array in the condition

  can [:read, :index], :stores, :id => user_stores
  can [:read, :index, :create, :update], [:calls, :change_requests], :store_id => user_stores

That works as required.

3
On

Try changing the ability to:

can :index, Call, :store => { area_id: user.area_id }