Using Rails CanCan gem to handle has_and_belongs_to_many situation

I have the following:

  • User model that has_and_belongs_to_many Restaurants and vice versa.
  • Restaurant model that has_and_belongs_to_many Food and vice versa.

In my ability.rb file, I want to indicate that the user can control the power in the has_and_belongs_to restaurants (i.e. restaurants in user.restaurants ).

I have it right now:

 class Ability include CanCan::Ability def initialize(user) # a user can only manage meals of restaurants he has access to can :manage, Meal do |meal| meal.restaurant_ids & user.restaurant_ids #...this doesn't work... end end end 

What is the best way to do this?

I consulted https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks , but I still don't know.

+4
source share
1 answer

The & operator in an array will always return an array. An empty array is not considered false, so it will always pass. Try to check if it is present (not empty).

 (meal.restaurant_ids & user.restaurant_ids).present? 
+7
source

All Articles