Vinícius
Vinícius

Reputation: 57

rails update_all for ActiveRecord Relation using 'having' don't work

Sample:

a = Model.join("...").where("...").group("...")
b = Model.join("...").where("...").group("...").having("...")

If I do:

a.class gives me ActiveRecord::Relation. Same with b.class.

When I do:

a.length i get 1000. And b.length i get 50

And finally, if i do:

a.update_all(field:'...')
=> 1000

b.update_all(field:'...')
=> 1000

Not 50, as I was expecting.

Why this happen? Is there any way to deal with this?

Upvotes: 0

Views: 425

Answers (1)

Rajesh Kolappakam
Rajesh Kolappakam

Reputation: 2125

update_all only takes the constraints from your query and ignores the group and having clauses.

Here is the source code of update_all

def update_all(updates)
    .....
    # HERE IS THE RELEVANT CODE
    # It extracts only the constraints, limit and order clauses. It ignores the rest
    stmt.take(arel.limit)
    stmt.order(*arel.orders)
    stmt.wheres = arel.constraints
    .....
end

I guess you would have to do it in two steps, execute your query with the having clause and get the list IDs for the 50 records that match and then do an update_all on these records using an IN clause

Upvotes: 1

Related Questions