Ruby: AND clause if conditional operator under CanCan gem

108 Views Asked by At

Here is the sceanrio: I'm using CanCan gem and try to implement a :read ability accompanied with 2 AND conditions

can :read,    Truck,  :product => {:company_id => user.company_id}

Now here I wanted to have and additional condition checking for a column value as follows:

can :read,    Truck,  :product => {:company_id => user.company_id, :category_id => user.category_id}

But the above statement throws error in active_adapter saying "Undefined table_name for nil class"

Also the second set of condition category_id needs to be present only if a flag "check_category_id_flag" is checked. At the end I want something as below to work for me:

can :read,    Truck,  :product => {:company_id => user.company_id, 
( user_role.check_category_id_flag? ? :category_id => user.category_id : 1 == 1)}
1

There are 1 best solutions below

0
mechnicov On

You can combine conditions like this

can :read, Truck do |truck|
  truck.product.company == user&.company && truck.product.category == user&.category
end