Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 重写rails update_all方法_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 重写rails update_all方法

Ruby on rails 重写rails update_all方法,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我需要重写rails(activerecord)update\u all方法,以便它总是在字段更新updated\u。我应该如何实现这一目标 您可以覆盖模型中的update_all方法: def self.update_all(attr_hash) # override method attr_hash[:updated_at] = Time.now.utc super( attr_hash ) end 将以下代码放入文件/config/initializers/updat

我需要重写rails(activerecord)
update\u all
方法,以便它总是在字段更新
updated\u。我应该如何实现这一目标

您可以覆盖模型中的update_all方法:

 def self.update_all(attr_hash) # override method
    attr_hash[:updated_at] = Time.now.utc
    super( attr_hash )
 end

将以下代码放入文件
/config/initializers/update\u all\u with_touch.rb

class ActiveRecord::Relation

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

    now = Time.now

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

    update_all_without_touch(updates, conditions, options)
  end
  alias_method_chain :update_all, :touch

end

方法
update\u all
被我定义的方法
update\u all\u with\u touch
替换,原始的
update\u all
重命名为
update\u all\u without\u touch
。新方法修改了
upgrades
对象,将
updated\u的更新注入到
,然后调用原始的
update\u all

我需要在多个模型中使用这种行为,因此我正在寻找一种可以跨模型工作的方法。因此,添加一个ActiveRecord超类并将函数添加到其中。然后,它将适用于您的所有模型。该解决方案可以工作,但我不清楚它到底是如何工作的。有哪些方法可以在不更新的情况下更新\u all\u,或者在更新的情况下更新\u all\u?此外,代码中使用了不同格式的update_,因此更新可以是散列、数组或字符串。我可以检查类型并将更新的_at参数合并为散列,这是可行的,但是当它是数组还是字符串时呢?@user523146我修改了代码段以处理字符串和数组,并添加了一些解释。更新文件并重新启动服务器以查看更改。我已将
替换为\u updated\u at
替换为
并使用\u touch
进行澄清。在期望rails控制台发生相同更改的同时,全局覆盖此方法是否有帮助@鲍德里克
alias_method_chain :update_all, :touch