Rails 部分更新哈希值问题
Rails ActiveRecord 支持部分更新,并且在大多数情况下运行良好,但如果我们序列化了哈希字段,AR 每次都会执行更新,即使没有任何更改。这是来自 Rails 控制台的示例:
### 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
有任何解决方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果 x.changed 则保存 x.save?
http://ar. rubyonrails.org/classes/ActiveRecord/Dirty.html
x.save if x.changed?
http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html