ruby-on-rails - 即使没有更改,有没有办法防止 rails 中的序列化属性更新?

标签 ruby-on-rails ruby-on-rails-3 serialization update-attributes

这可能是所有新用户迟早会发现有关 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/

相关文章:

ruby-on-rails - Haml管道分隔的多行语句语法突出显示

ruby-on-rails - Rails 4将局部变量获取到js.erb文件

ruby-on-rails - Sunspot 自动完成插件无法正常工作?

c# - 如何在 C# MVC Controller 操作中将动态对象序列化为 JSON?

c# - 将类实例存储到文件/数据库的最佳方式

Python:防止缓存减慢我的速度

ruby-on-rails - 运行 RSpec 测试时出现 NoMethodError

ruby-on-rails - 有没有好的 ruby​​ (on rails) 编辑器?

jquery - 如何让相同的 javascript 代码响应多个 ajax 调用?

javascript - 使用 AJAX 重定向到 Rails 路径