将 will_paginate 与多个模型(Rails)一起使用 [英] Using will_paginate with multiple models (Rails)

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

问题描述

很确定我在这里遗漏了一些非常简单的东西:

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

我正在尝试显示一系列页面,其中包含两种不同模型的实例 - 配置文件和组.我需要他们按名称属性排序.我可以选择每个模型的所有实例,然后对它们进行排序和分页,但这感觉草率且效率低下.

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.

一些代码行(未测试)

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天全站免登陆