将对多个表进行分页
我有下表:
- 用户
- 帐户(用户 has_one 帐户)
- 图片(用户 has_many 图片)
我想显示用户及其相关帐户和图片。这是一个典型的 N+1 查询问题,我使用 急切加载。
User.includes(:account, :pictures).all
我正在尝试使用 will_paginate
gem。如何将这种急切加载机制包含到 will_paginate
中?
我在这里发现了类似的问题:将 will_paginate 与多个模型 (Rails) 一起使用。但答案中的链接不合适,而且答案本身也很旧。此外,它使用原始 sql 查询,这是我不喜欢的。
我想要的输出如下:
user.name account.field1 account.field2 picture.count
abc1 abcf1 abcf2 4
zxc zxcf1 zxcf2 7
所以基本上当我执行 user.name
时,它不会执行查询,而只是从变量中获取数据; 同样,当我执行 user.account.field1
时,它应该从变量中获取它而不是执行查询。
I have following tables :
- users
- accounts ( user has_one account )
- pictures ( user has_many pictures )
I want to display a User along with its related account and pictures. This is a typical N+1 queries problem and I solved it using eager loading.
User.includes(:account, :pictures).all
I am trying to use will_paginate
gem. How do I include this eager loading mechanism into will_paginate
?
I found a similar question here: Using will_paginate with multiple models (Rails). But the links in the answer are out of place and the answer itself is quite old. Furthermore, it uses raw sql queries, which I don't prefer.
I want the output as follows :
user.name account.field1 account.field2 picture.count
abc1 abcf1 abcf2 4
zxc zxcf1 zxcf2 7
So basically when I do user.name
, it will not execute a query but just get the data from the variables;
same way when I do user.account.field1
it should fetch it from the variable and not execute a query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
paginate
方法与all
方法类似。因此,您可以简单地执行以下操作:OR
注意:
will_paginate
gem 在Array
类上提供了一个方便的方法分页:The
paginate
method is similar toall
method. So you can simply do this:OR
Note:
The
will_paginate
gem provides a convenience method on theArray
class for pagination:我最终在数组上使用分页而不是 gem 本身。
I finally used pagination on a array rather than the gem itself.