Why update_attributes doesn't update an attribute, but update does?

1.8k Views Asked by At

Rails version: Rails 5.1.1

Ruby Version: ruby-2.4.0 [ x86_64 ]

Local Server:

Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.0-p0), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000

I have a existing model called User and later I added the attribute last_name.

Then, trying to update the newly created field(last_name) with other fields, I used:

user.update_attributes(first_name: 'praaveen', last_name:'vr')

For update_attributes, this updates first_name but not the last_name attribute:

rails log:

UPDATE "users" SET "updated_at" = $1, "first_name" = $2 WHERE "users"."id" = $3  [["updated_at", "2017-09-20 14:19:26.174311"], ["first_name", "praaveen"], ["id", 156]]

I then tried with:

user.update(first_name: 'praaveen', last_name:'vr')
user.update_columns(first_name: 'praaveen', last_name:'vr')

These methods update first_name and last_name as expected.

rails log:

UPDATE "users" SET "updated_at" = $1, "first_name" = $2, "last_name" = $3 WHERE "users"."id" = $4  [["updated_at", "2017-09-20   14:15:23.623292"], ["first_name", "praaveen"], ["last_name", "vr"], ["id", 156]]

Any idea what's going?

Adding few observations

a. It updates random like once in 10 or 15 times update.

b. Any problem with puma multi threading?

2

There are 2 best solutions below

0
On

I had a similar issue with a JSONB field that wouldn't want to be saved with update and not even with update_attribute...

I ended up marking the field to be updated with:

attribute_name_will_change!

And that worked! Hopefully this may help someone one day.

3
On

You might be facing some accessors trouble as described here.

As explained in the article:

Doing the following will merrily return true, but will not update the status attribute.

@user.update_attributes(:status => 'active')