分享 will paginate 的 total_entries 方法

xiaoronglv · 2014年07月10日 · 最后由 teddy_1004 回复于 2014年11月04日 · 1773 次阅读

Old(共查询了 3 次数据库)

posts_controller.rb

@total_count = Post.count # hit db
@posts = Post.paginate(page: params[:page]) # hit db twice

其实分页后的对象已经包含 total count 的信息了,没有必要再查一次数据库。直接使用 ** total_entries** 方法既可

pry(main)> posts = Post.desc(:id).paginate(page: 1)

pry(main)> posts.class

=> WillPaginate::Collection

pry(main)> posts.instance_variables

=> [:@current_page, :@per_page, :@total_entries]

pry(main)> posts.instance_eval {p @total_entries}

=> 3237

After(共查询了 2 次数据库)

posts_controller.rb

@posts = Post.desc(:id).paginate(page: params[:page]) # hit db twice
@total_count = @post.total_entries # 其实直接在 view 中调用就 ok 了

我后知后觉,今天才发现这个方法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号