对多个模型使用will_paginate(Rails) [英] Using will_paginate with multiple models (Rails)

查看:60
本文介绍了对多个模型使用will_paginate(Rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以肯定的是,我在这里遗漏了一些非常简单的东西:

Pretty sure that I'm missing something really simple here:

我正在尝试显示一系列页面,其中包含两个不同模型(个人档案"和组")的实例.我需要它们通过其name属性进行排序.我可以为每个模型选择所有实例,然后对它们进行排序和分页,但这感觉草率且效率低下.

I'm trying to display a series of pages that contain instances of two different models - Profiles and Groups. I need them ordering by their name attribute. I could select all of the instances for each model, then sort and paginate them, but this feels sloppy and inefficient.

我正在使用mislav-will_paginate,想知道是否有更好的方法来实现这一目标?像这样:

I'm using mislav-will_paginate, and was wondering if there is any better way of achieving this? Something like:

[Profile, Group].paginate(...)

会很理想!

推荐答案

好问题,我几次遇到相同的问题.每次,我都通过基于sql联合编写自己的sql查询来结束它(它与sqlite和mysql配合良好).然后,您可以通过传递结果来使用Will分页( http://www.pathf.com/blogs/2008/06/how-to-use-will_paginate-with-non-activerecord-collectionarray/).不要忘记执行查询以计算所有行.

Good question, I ran into the same problem a couple of times. Each time, I ended it up by writing my own sql query based on sql unions (it works fine with sqlite and mysql). Then, you may use will paginate by passing the results (http://www.pathf.com/blogs/2008/06/how-to-use-will_paginate-with-non-activerecord-collectionarray/). Do not forget to perform the query to count all the rows.

一些代码行(未经测试)

Some lines of code (not tested)

my_query = "(select posts.title from posts) UNIONS (select profiles.name from profiles)"
total_entries = ActiveRecord::Base.connection.execute("select count(*) as count from (#{my_query})").first['count'].to_i

results = ActiveRecord::Base.connection.select_rows("select * from (#{my_query}) limit #{limit} offset #{offset}")

它被过度杀伤了吗?也许可以,但是您的查询次数最少,结果也保持一致.

Is it overkilled ? Maybe but you've got the minimal number of queries and results are consistent.

希望有帮助.

注意:如果从http参数获取偏移值,则应使用sanitize_sql_for_conditions(即sql注入....)

Note: If you get the offset value from a http param, you should use sanitize_sql_for_conditions (ie: sql injection ....)

这篇关于对多个模型使用will_paginate(Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆