Rails的哈希部分更新问题 [英] Rails partial updates problem with hashes
本文介绍了Rails的哈希部分更新问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
###创建类和表###
>>类别Xx<的ActiveRecord :: Base的;序列化:params;结束
=> Object
>> ActiveRecord :: Base.connection.executeCREATE TABLE xxes(id serial,params text)
SQL(43.8ms)CREATE TABLE xxes(id serial,params text)
=> #<的PGresult:0x112113380>
###创建记录###
>> r = Xx.create(:params => {:a => 1})
SQL(0.9ms)INSERT INTOxxes(params)VALUES('---
: a:1
')RETURNINGid
=> #< Xx id:1,params:{:a => 1}>
###查找此记录###
>> x = Xx.find(1)
Xx Load(2.5ms)SELECTxxes。* FROMxxesWHERExxes。id= 1 LIMIT 1
=> #< Xx id:1,params:{:a => 1}>
###不变并调用保存###
>> x.save
AREL(1.1ms)UPDATExxesSETparams='---
:a:1
'WHERExxes。id= 1
=> true
是否有任何解决方法?
解决方案
x.save if x.changed?
http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html
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?
解决方案
x.save if x.changed?
http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html
这篇关于Rails的哈希部分更新问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文