[英]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? 我想将其用于特定型号,该怎么做?
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中
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.