这可能是所有新用户迟早会发现有关 Rails 的事情之一。我刚刚意识到 rails 正在使用 serialize 关键字更新所有字段,而没有检查内部是否真的发生了任何变化。在某种程度上,这是对通用框架做的明智之举。
但是有没有办法覆盖这种行为?如果我可以跟踪序列化字段中的值是否已更改,是否有办法防止它被推送到更新语句中?我尝试使用“update_attributes”并将哈希限制为感兴趣的字段,但 rails 仍然更新所有序列化的字段。
建议?
最佳答案
是的,这也困扰着我。这是我为 Rails 2.3.14(或更低版本)所做的:
# config/initializers/nopupdateserialize.rb
module ActiveRecord
class Base
class_attribute :no_serialize_update
self.no_serialize_update = false
end
end
module ActiveRecord2
module Dirty
def self.included(receiver)
receiver.alias_method_chain :update, :dirty2
end
private
def update_with_dirty2
if partial_updates?
if self.no_serialize_update
update_without_dirty(changed)
else
update_without_dirty(changed | (attributes.keys & self.class.serialized_attributes.keys))
end
else
update_without_dirty
end
end
end
end
ActiveRecord::Base.send :include, ActiveRecord2::Dirty
然后在您的 Controller 中使用:
model_item.no_serialize_update = true
model_item.update_attributes(params[:model_item])
model_item.increment!(:hits)
model_item.update_attribute(:nonserializedfield => "update me")
etc.
或者,如果您不希望序列化字段在创建后发生任何更改,则在您的模型中定义它(但 update_attribute(:serialized_field => "update me"仍然有效!)
class Model < ActiveRecord::Base
serialize :serialized_field
def no_serialize_update
true
end
end
关于ruby-on-rails - 即使没有更改,有没有办法防止 rails 中的序列化属性更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745213/