将两个的ActiveRecord ::关系用或不和,返回的关系,而不是一个数组以便在将来进行分页 [英] Combine two ActiveRecord::Relation with OR, not AND, returning a Relation and not an Array to be able to paginate later

查看:134
本文介绍了将两个的ActiveRecord ::关系用或不和,返回的关系,而不是一个数组以便在将来进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A B 是其返回相同类型的对象的ActiveRecord ::关系的对象(在此Micropost对象情况下)

a and b are ActiveRecord::Relation objects which return the same type of objects(Micropost objects in this case)

a.class
=> ActiveRecord::Relation
b.class
=> ActiveRecord::Relation
a.first
=> Micropost(...) 
b.first
=> Micropost(...) #They both return the same type of objects
c=a+b
c.class
=> Array #This is not what i'm looking for
c=a|b
c.class
=> Array #Not what i'm looking for either
c=(a or b)
c.class
=> ActiveRecord::Relation #But it is just a, so it's wrong
c==a
=> true
a.merge(b)
=> []  #It merges with AND which in my case results in an empty array

有没有一些方法来或两者关系的对象,并返回在Rails的3.2.11另一个关系对象?我是否需要使用一些宝石,如 squeel 办呢?

如果它不能做到:为什么不能做?我可以从分页 A产生的阵列| B 不从数据库中装载每个记录
? 如果是可以做到的:任何人都可以请写出如何做到这一点的例子

If it can't be done: Why it can't be done? Can I paginate the array resulting from a|b without loading every record from the database?
If it can be done: Could anyone please write an example of how to do it?

在此先感谢。

编辑:我抄错变量变成code块,B是不是一个ActiveRecord ::关系,它实际上是一个数组,这就是为什么a.merge(二)返回[]。 是我的错。

I copied the wrong variables into the block of code, b was not an ActiveRecord::Relation, it was actually an array and that is why a.merge(b) returned []. My fault.

TLDR:问题是错误的,阵列可以分页:)

TLDR: Question is wrong, and array can be paginated :)

推荐答案

对于你的问题:<?code>我可以分页从产生的数组| B没有从数据库中装载的每个记录

,您可以分页阵列。只有你所要做的就是要求will_paginate /阵列文件在您使用分页阵列。如果您在很多地方使用那么它能够更好地将其添加在配置/初始化。而其阵,所以它不会从数据库中每个时间(即)查询触发一次加载每个记录。要装入关联中,你可以使用渴望负荷阵列使用包括

Yes, you can paginate array. Only you need to do is require 'will_paginate/array' file where your are using paginate for array. If you are using in many place then its better to add it in config/initializers. And its array so it won't load every record from database each time (i.e.) query is fired only once. To load association you can use eager load on array using include.

这篇关于将两个的ActiveRecord ::关系用或不和,返回的关系,而不是一个数组以便在将来进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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