Rails partial updates problem with hashes

大兔子大兔子 提交于 2019-12-11 06:25:21

问题


Rails ActiveRecord support partial updates and it works well most of the time, but in case we have serialized hash field AR executes update every time, even if nothing has been changed. Here example from rails console:

### Create class and table ###
>> class Xx < ActiveRecord::Base; serialize :params; end
=> Object 

>> ActiveRecord::Base.connection.execute "CREATE TABLE xxes(id serial, params text)"
SQL (43.8ms)  CREATE TABLE xxes(id serial, params text)
=> #<PGresult:0x112113380>


### Create record ###
>> r = Xx.create(:params => {:a => 1})
SQL (0.9ms)  INSERT INTO "xxes" ("params") VALUES ('--- 
:a: 1
') RETURNING "id"
=> #<Xx id: 1, params: {:a=>1}>


### Find this record ### 
>> x = Xx.find(1)
Xx Load (2.5ms)  SELECT "xxes".* FROM "xxes" WHERE "xxes"."id" = 1 LIMIT 1
=> #<Xx id: 1, params: {:a=>1}>


### Change nothing and call save ###
>> x.save
AREL (1.1ms)  UPDATE "xxes" SET "params" = '--- 
 :a: 1
' WHERE "xxes"."id" = 1
=> true 

Are there any workaround?


回答1:


x.save if x.changed?

http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html



来源:https://stackoverflow.com/questions/7448083/rails-partial-updates-problem-with-hashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!