Search code examples
ruby-on-railscancan

CanCan not filtering @products in Index


I am working on a Rails 3.2 application with Devise and CanCan.

My user model is User, and I want to restrict the access to the Product resource to the ones created by the User. The relevant code snippets:

app/models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    if user
      can :manage, Product, user_id: user.id
    end
  end
end

app/controller/products_controller.rb

class ProductsController < ApplicationController
  load_and_authorize_resource
       ..
end

config/routes.rb

...
devise_for :products

resources :products do
  resources :sizes
end
...

Everything is working as expected: users cannot see, edit, etc... products not created by them. But problem is that if a user access the product index at /products then all products are visible.

How can I do to filter the relevant products in the index page?

I have googling around, and try authorize! :index, Ability in the index action together with can :index, Product, user_id: user.id, but then the user cannot access at all at the Index page.

Any help is appreciated.


Solution

  • This is not really a authorization issue. Instead should you scope you query, in your index action for the Product controller. Eg something like this:

    class ProductsController < ApplicationController
      def index
        @products = current_user.products
      end
    end