Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Triggers Update on Serialized Attribute Every Time

I have a simple user model with a name and settings. After every save of user AREL is performing an update to the settings column. For example:

user = User.find_by_name('kevin')
user.save

(0.3ms)  UPDATE "users" SET "updated_at" = '2011-10-20 19:58:06.363541', "settings" = '--- {}' WHERE "users"."id" = 1

None of the other fields are updated when calling save. Is this expected behavior? Why is it performing the update? Can it be turned off to not change if the serialized contents haven't changed? I've uploaded the sample project used to create a minimum case:

http://cl.ly/0p0j3Z3Y0L1x1I1p3Z0g

like image 913
Kevin Sylvestre Avatar asked Feb 23 '23 15:02

Kevin Sylvestre


1 Answers

This is expected behavior. It is very difficult to detect changes within a serialized attribute, so they are updated on every save.

Consider the following (ruby 1.8.7) irb session:

ruby-1.8.7-p352 :001 > x = "--- \n:b: 2\n:a: 1\n"
 => "--- \n:b: 2\n:a: 1\n" 
ruby-1.8.7-p352 :002 > y = "--- \n:a: 1\n:b: 2\n"
 => "--- \n:a: 1\n:b: 2\n" 
ruby-1.8.7-p352 :003 > x == y
 => false 
ruby-1.8.7-p352 :004 > YAML.load(x) == YAML.load(y)
 => true
like image 200
moritz Avatar answered May 05 '23 13:05

moritz