简体   繁体   English

覆盖特定模型的update_all方法Rails 4.2

[英]Overriding update_all method for specific models Rails 4.2

I need to override the rails update_all method so that it will update updated_at field for specific models. 我需要重写rails update_all方法,以便针对特定模型更新update_at字段。

I have added following module in app/config/intializer/xyzfile.rb : 我在app / config / intializer / xyzfile.rb中添加了以下模块:

module ActiveRecord
  class Relation
    def update_all_with_updated_at(updates)
      case updates
        when Hash
          updates.reverse_merge!(updated_at: Time.now)
        when String
          updates += ", updated_at = '#{Time.now.to_s(:db)}'"
        when Array
          updates[0] += ', updated_at = ?'
          updates << Time.now
      end
      update_all_without_updated_at(updates)
    end
    alias_method_chain :update_all, :updated_at
  end
end

I want to use this for specific models, How can I do this? 我想将其用于特定型号,该怎么做?

  • Adding updated_at in each update_all is one of the solutions but I am looking for a solution with which I can override update_all method. 解决方案之一是在每个update_all中添加updated_at,但我正在寻找一种可以覆盖update_all方法的解决方案。

Put the following code in a file /config/initializers/update_all_with_touch.rb Place this block of code in 将以下代码放在文件/config/initializers/update_all_with_touch.rb中

app/config/intializer/update_all_decorate.rb 应用程序/配置/初始化器/ update_all_decorate.rb

class ActiveRecord::Relation

  def update_all_decorate(updates, conditions = nil, options = {})

    current_time = Time.now

    # Inject the 'updated_at' column into the updates
    case updates
      when Hash;   updates.merge!(updated_at: current_time)
      when String; updates += ", updated_at = '#{current_time.to_s(:db)}'"
      when Array;  updates[0] += ', updated_at = ?'; updates << current_time
    end

  end
  alias_method_chain :update_all, :touch
end

alias_method_chain block is responsible for overriding the default behavior of update_all method. alias_method_chain块负责覆盖update_all方法的默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM