Search code examples
ruby-on-railsrubycancannested-resources

CanCan deeply nested resources


I have a routes.rb that looks like this:

resources :restaurants, :shallow => true do
  resources :orders do
    resources :foods
  end
  resources :categories do
    resources :foods
  end
end

something like this in my ability.rb works,

if user.role? :owner
  can :manage, Category, :restaurant => {:user_id => user.id}
  ...

but deeper nesting appears to be a problem with shallow nesting.

  can :manage, Food, :category => {:restaurant => {:user_id => user.id}}
end

Any idea on how to get CanCan to handle nesting that is as deep as the last example?


Solution

  • I don't think it's possible. You will have to do it yourself using a block:
    https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks

    can :manage, Food do |food|
        food.categories.joins(:restaurant).where("restaurants.user_id = ?", user.id).any?
    end
    

    What do you want exactly? Users can only manage food if it belongs to a restaurant owned by the user though categories?