How to paginate with cancan?

I am looking to do pagination with cancan, however it is not obvious how to integrate this with gems such as will_paginate.

Ideally, cancan load_resource will delegate will_paginate and add additional conditions. For example, in cancan I declared guest users

can :read, Post, :published => true 

and this is automatically handled by load_resource. However, I would like the will_paginate page to go through all these results.

Any ideas.

Hi

Brad

+6
source share
2 answers

It is easy to do with kaminari https://github.com/amatsuda/kaminari

in my PostsController I just do

  before_filter :load_by_pagination, :only => :index def load_by_pagination @posts = Post.accessible_by(current_ability).order("published_date desc").page params[:page] end 

Note that kaminari works correctly with the new rails3 ActiveRelation framework, so you can combine methods together to create a scope. And since CanCan is also ActiveRelation friendly, they both just cling together.

+10
source

You can also do something like this:

 class PostsController def index @posts = @posts.page(params[:page]) ... 
+6
source

Source: https://habr.com/ru/post/887809/


All Articles