How to do pagination with cancan?
Asked Answered
G

2

7

I'm looking to do pagination with cancan however it's not obvious how to integrate this with gems such as will_paginate.

Ideally cancan's load_resource will delegate to will_paginate and add extra conditions. For example in cancan I've declared guest users

can :read, Post, :published => true

and this is handled automatically by load_resource. However I'd then like to have will_paginate page through all these results.

Any ideas.

Regards

Brad

Georgiana answered 11/5, 2011 at 9:38 Comment(0)
G
10

This is simple 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 properly with the new rails3 ActiveRelation framework so it's possible to chain methods together to build up scope. And as CanCan is also ActiveRelation friendly they both just chain together.

Georgiana answered 11/5, 2011 at 10:2 Comment(0)
G
6

You can also do something like this:

class PostsController 

  def index
    @posts = @posts.page(params[:page])     
  ...
Groove answered 8/3, 2012 at 14:27 Comment(2)
Yes, but then if nothing is accessible, cancan sets @posts to nil and the world ends... Or is there another way?Chisolm
this should be avoided unless you want to pull all @posts from the database prior to paging.Eared

© 2022 - 2024 — McMap. All rights reserved.