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.

Leave a Comment

error code: 523