Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a CanCan ability with join?

I'm using CanCan 1.6.10 with Rails 3.2.13

I'm setting up my Abilities for my Staff (rather than User) model. I have:

class Ability
    include CanCan::Ability
    def initialize(staff)
        if staff.role? :driver
            can :read, User.joins(:orders => {:delivery_slot => :driver}).where("driver_id = ?", staff.id)

I've tested the joins where in the console and it returns 7 records. When I test the ability it fails to return any:

User.accessible_by(Ability.new(Staff.find(7)))

The SQL from the last query .to_sql shows as:

SELECT `users`.* FROM `users` WHERE (1=0)

whereas User.joins(:orders => {:delivery_slot => :driver}).where("driver_id = ?", 7) gives:

SELECT `users`.* FROM `users` INNER JOIN `orders` ON `orders`.`user_id` = `users`.`id` INNER JOIN `delivery_slots` ON `delivery_slots`.`id` = `orders`.`delivery_slot_id` INNER JOIN `staff` ON `staff`.`id` = `delivery_slots`.`driver_id` WHERE (driver_id = 7) 
like image 783
Mark Robinson Avatar asked Oct 25 '25 09:10

Mark Robinson


1 Answers

Have you tried a hash of conditions rather than having explicit joins?

can :read, User, :orders=>{:delivery_slot=>{:driver=>{:id => staff.id}}}
like image 200
Subhas Avatar answered Oct 27 '25 00:10

Subhas