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)
Have you tried a hash of conditions rather than having explicit joins?
can :read, User, :orders=>{:delivery_slot=>{:driver=>{:id => staff.id}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With