How do I do an `update ... from` in ActiveRecord?

Viewed 303

I would like to do an update ... from, or an update using a CTE, but using ActiveRecord. Ideally so I can take advantage of in_batches.

For example, Person has many Things and I'd like to cache their first Thing. I'd imagine it would work something like this.

Person
  .in_batches
  .from(
    Thing.select(
      :id, 
      :people_id, 
      "rank() over (partition by people_id order by created_at asc) as thing_rank"
    )
   )
   .where(
     "things.thing_rank": 1,
     "people.id": :people_id
   )
  .update_all(cached_thing_id: "things.id")

But I can't figure any combination that works.

Alternatively, is there a way to use in_batches while manually writing out the SQL? And I'm not attached to the subquery method, a CTE or temporary view is fine.

0 Answers
Related