开发者

Is it possible to combine will_paginate with find_by_sql?

开发者 https://www.devze.com 2022-12-25 02:54 出处:网络
In my Rails application I want to use the will_paginate gem to pa开发者_运维百科ginate on my SQL query. Is that possible? I tried doing something like this but it didn\'t work:

In my Rails application I want to use the will_paginate gem to pa开发者_运维百科ginate 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.


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*.


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


Try this:

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

What will_paginate and rails version are you using?

0

精彩评论

暂无评论...
验证码 换一张
取 消