ActiveRecord 分页 returns 空结果

ActiveRecord paginate returns empty results

根据 will_paginate's documentation,它应该能够调用 MyModel.paginate 以使用 SQL 查询加载一页结果,该查询仅加载所需的行。但是即使执行了正确的查询(对 Oracle 数据库),我总是得到空结果。对数组分页执行相同的操作会起作用。为什么 ActiveRecord::Base.paginate 不起作用? (Rails 2.3 / JRuby 1.7)

>> users = User.paginate(:all, :page => 1, :per_page => 10)
=> []
# query performed, verified correct: select * from (SELECT * FROM "USERS" WHERE ("USERS".is_deleted = 0 or "USERS".is_deleted is NULL)  ORDER BY id) where rownum <= 10
>> users.size
=> 0
>> users.total_entries
=> 0
# regular pagination over the result works but is not optimal as it loads all records
>> u2 = User.find(:all).paginate(:page => 1, :per_page => 10)
=> [#<User user_id: 4015857, ...> ... ]
>> u2.size
=> 10
>> u2.total_entries
=> 32449

从参数列表中删除 :all:

users = User.paginate(:page => 1, :per_page => 10)

虽然我不知道确切的原因可能与旧的 rails 2.3 和 will_paginate 版本有关。解决方法很简单:从 AR 查找器结果中滚动您自己的 WillPaginate::Collection,例如

# given page and per_page parameters
count = User.count(:all)
return WillPaginate::Collection.create(page, per_page, count) { |pager|
    pager.replace(User.find(:all, :offset => (page - 1) * per_page, :limit => per_page)
}