I tried this after a while, and I finally got to the point that CanCan does not allow you to allow collection of records. For instance:
ads_controller.rb
def index @ads = Ad.where("ads.published_at >= ?", 30.days.ago).order("ads.published_at DESC") authorize! :read, @ads end
ability.rb
def initialize(user) user ||= User.new # Guest user if user if user.role? :admin # Logged in as admin can :manage, :all else # Logged in as general user can :read, Ad can :read_own, Ad, :user_id => user.id can :create, Ad end else # Not logged in (Guest) can :read, Ad end end
This results in an unauthorized access message when trying to access the index action.
You are not authorized to access this page.
However, if you change the authorization call in the index action to check the Ad class and not the collection, for example
def index @ads = Ad.where("ads.published_at >= ?", 30.days.ago) authorize! :read, Ad end
... it works great.
Any help in explaining this would be greatly appreciated.
Thanks in advance.
ps. Initially, I was getting redirect cycles when trying to solve this problem. It turned out that with the recommended rescue_from, you got into the application controller to give you good error messages. If your root_path is installed in the same place where you log in! the call is incorrect (or does not work), you will get a redirect cycle. Comment on rescue_from Found out that this is the hard way.
source share