Converting an array of objects to ActiveRecord::Relation

后端 未结 5 1425
醉酒成梦
醉酒成梦 2020-12-04 07:00

I have an array of objects, let\'s call it an Indicator. I want to run Indicator class methods (those of the def self.subjects variety, scopes, etc

5条回答
  •  甜味超标
    2020-12-04 07:41

    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.

提交回复
热议问题