Is it possible to combine will_paginate with find_by_sql?
Asked Answered
R

3

20

In my Rails application I want to use the will_paginate gem to paginate on my SQL query. Is that possible? I tried doing something like this but it didn't work:

@users = User.find_by_sql("
    SELECT u.id, u.first_name, u.last_name, 
     CASE 
      WHEN r.user_accepted =1 AND (r.friend_accepted =0 || r.friend_accepted IS NULL)
       .........").paginate(
                  :page => @page, :per_page => @per_page, 
                  :conditions => conditions_hash,
                  :order => 'first_name ASC')

If not, can you recommend a way around this? I don't want to have to write my own pagination.

Robbery answered 29/3, 2010 at 4:56 Comment(0)
I
52

Use paginate_by_sql, i.e.

sql = " SELECT * 
        FROM   users
        WHERE  created_at >= ?
        ORDER  BY created_at DESC "

@users = User.paginate_by_sql(
  [sql, 2.weeks.ago],
  page: @page,
  per_page: @per_page
)

As a general rule any finder can be paginated by replacing the find* with paginate*.

Invasion answered 29/3, 2010 at 5:21 Comment(1)
With binds: paginate_by_sql([sql, binds], page: # etc..Conjuncture
R
-2

User.paginate_by_sql(sql, :page => params[:page], :per_page => 10)

Raddled answered 14/5, 2015 at 12:5 Comment(0)
S
-3

Try this:

@users = User.find_by_sql 
@users = @users.paginate

What will_paginate and rails version are you using?

Sent answered 29/3, 2010 at 5:8 Comment(1)
In your solution, pagination is applied on the result set returned by the find_by_sql. So you might have to deal with a large result-set and hence the system has to perform redundant computing.Invasion

© 2022 - 2024 — McMap. All rights reserved.