Converting an array of objects to ActiveRecord::Relation
You can convert an array of objects arr
to an ActiveRecord::Relation like this (assuming you know which class the objects are, which you probably do)
MyModel.where(id: arr.map(&:id))
You have to use where
though, it's a useful tool which you shouldn't be reluctant to use. And now you have a one-liner converting an array to a relation.
map(&:id)
will turn your array of objects to an array containing only their id's. And passing an array to a where clause will generate a SQL statement with IN
that looks something like:
SELECT .... WHERE `my_models`.id IN (2, 3, 4, 6, ....
Keep in mind that the ordering of the array will be lost - But since your objective is only to run a class method on the collection of these objects, I assume it won't be a problem.
How can I convert an Array of objects to an ActiveRecord::Relation? Preferably without doing a where each time.
You cannot convert an Array to an ActiveRecord::Relation since a Relation is just a builder for a SQL query and its methods do not operate on actual data.
However, if what you want is a relation then:
for ActiveRecord 3.x, don’t call
all
and instead callscoped
, which will give back a Relation which represents the same records thatall
would give you in an Array.for ActiveRecord 4.x, simply call
all
, which returns a Relation.
When running a
def self.subjects
type method on an ActiveRecord::Relation, how do I access that ActiveRecord::Relation object itself?
When the method is called on a Relation object, self
is the relation (as opposed to the model class it’s defined in).
Well, in my case, I need to converting an array of objects to ActiveRecord::Relation as well as sorting them with a specific column(id for instance). Since I'm using MySQL, the field function could be helpful.
MyModel.where('id in (?)',ids).order("field(id,#{ids.join(",")})")
The SQL looks like:
SELECT ... FROM ... WHERE (id in (11,5,6,7,8,9,10))
ORDER BY field(id,11,5,6,7,8,9,10)
MySQL field function