views:

205

answers:

2

In my rails application I want to use will_paginate plugin to paginate on my 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 or a way that might work as I don't want to write my own pagination.

+1  A: 

Try this:

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

What will_paginate and rails version are you using?

jpartogi
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.
KandadaBoggu
Thanks for the input.
jpartogi
+3  A: 

Use paginate_by_sql, i.e.

sql = " SELECT * 
        FROM   users
        WHERE  created_at >= '#{2.weeks.ago}'
        ORDER BY created_at DESC "
@users =  User.paginate_by_sql(sql, :page => @page, :per_page => @per_page)

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

KandadaBoggu