1

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 

有什么解决方法吗?

4

1 回答 1

1

x.save if x.changed?

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

于 2011-09-16T17:12:56.003 回答