问题
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
Is there some way to "OR" both Relation objects and return another Relation object in Rails 3.2.11? Do I need to use some gem such as squeel
to do it?
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?
Thanks in advance.
EDIT: 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: Question is wrong, and array can be paginated :)
回答1:
For you question: Can I paginate the array resulting from a|b without loading every record from the database?
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
.
来源:https://stackoverflow.com/questions/15054524/combine-two-activerecordrelation-with-or-not-and-returning-a-relation-and-no