Rails 部分更新哈希值问题

发布于 2024-12-05 12:06:56 字数 957 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文