DEV Community


Discussion on: Why is Rails ActiveRelation.update_all updating a different set of records?

coreyja profile image
Corey Alexander

I don't know what the magic/issue is with your first example, but I have an idea of how to make your workaround take a single query. I can't seem to get an example like this working with union(and on Rails 5.2 it gives a deprecation warning, about removing the delegation down into AREL) so I can't test this well myself.

But if you do NOT pluck the id, and simply pass a relation into the where clause for id it will do a sub-select for the update. I tried it with a simpler case and got the update_all to use a sub_select. So I think you should be able to do this in one query with:

comment = Comment.find(params[:id])

related_comments = comment.where(something: params[:something)
  .union(comment.where(something_else: params[:something_else]))
  .where(user_id: comment.user_id)

Comment.where(id: related_comments).update_all(receive_notifications: true)