Search code examples
ruby-on-railsruby-on-rails-3postgresqlcancanrails-activerecord

With CanCan, how do i limit ability based on association / child attribute


I have a db setup where there are many users, which have roles of member or admin. Each user has many cars. Each car has many timeslips

So, how do i limit a user's ability to edit a Timeslip only if he is the owner of the parent car.

In CanCan:

class Ability
    include CanCan::Ability

    def initialize(user)
        user ||= User.new # guest user (not logged in)
        if user.has_role? :admin
            can :manage, :all
        elsif user.has_role? :member
            can :manage, Car, :user_id => user.id
            can :manage, Timeslip, :car => {:user_id => user.id}
        end
    end
end

so the line can :manage, Timeslip, :car => {:user_id => user.id} is where i need some help.

Because Timeslip is an association/child of Car, i need to check that its parent car.user_id = the Cancan user.id

I thought how i wrote this is in line with the CanCan docs, but where have I gone wrong?


Solution

  • There might be a shorter way to write it, but this will work:

    can :manage, Timeslip do |timeslip|
         timeslip.car.user_id == user.id
    end