我需要覆盖rails(活动记录)update_all
方法,以便它始终更新updated_at
字段。我应该如何去实现这个目标?覆盖rails update_all方法
1
A
回答
4
将下面的代码在一个文件/config/initializers/update_all_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_all
它会自动添加参数:updated_at => Time.now
。
说明:
这个片段使用alias_method_chain
覆盖的update_all
默认:
alias_method_chain :update_all, :touch
方法update_all
由该方法update_all_with_touch
代替我定义了,原来update_all
被重命名update_all_without_touch
。新方法修改upgrades
对象以注入更新updated_at
,然后再调用原始的update_all
。
1
您可以在模型覆盖update_all方法:
def self.update_all(attr_hash) # override method
attr_hash[:updated_at] = Time.now.utc
super(attr_hash)
end
+0
我需要这种行为在多个模型中,因此我正在寻找一种可以跨模型工作的方法。 –
+0
因此,添加一个ActiveRecord超类并将函数添加到那里。然后它将适用于您的所有型号 – user2503775
相关问题
- 1. 覆盖rails activerecord touch方法
- 2. Rails - 覆盖别名方法
- 3. update_all与方法
- 4. spec for update_all方法在rails上的ruby
- 5. 覆盖方法
- 6. 覆盖方法
- 7. 覆盖方法
- 8. 覆盖方法
- 9. 覆盖'+'方法
- 10. 覆盖Rails中的宝石方法
- 11. Java方法覆盖 - “方法不会覆盖超级方法...”
- 12. 覆盖get方法
- 13. 覆盖Uploadify方法
- 14. 覆盖printf方法
- 15. C++方法覆盖
- 16. VideoJS覆盖方法
- 17. C++覆盖方法
- 18. 覆盖internalFrameClosing方法
- 19. 从覆盖方法
- 20. 覆盖/新方法
- 21. 覆盖shouldAutorotateToInterfaceOrientation方法
- 22. Java。覆盖方法
- 23. OnBackKeyPress覆盖方法
- 24. eclipse覆盖方法
- 25. Android方法覆盖
- 26. Backbone.Marionette覆盖方法
- 27. 覆盖OnCreateOptionsMenu方法
- 28. rails update_all插值
- 29. Rails的update_all
- 30. 调用覆盖方法,超类调用覆盖方法
此解决方案的工作原理,但我不清楚这是如何工作。有什么方法update_all_without_updated_at或update_all_with_updated_at?此外,代码中使用了不同格式的update_all,因此这些更新可以是散列,或数组或字符串。我可以检查类型并合并一个散列的updated_at参数,这是可行的,但是当它的数组或字符串呢? –
@ user523146我修改了片段来处理字符串和数组,并添加了一些解释。更新文件并重新启动服务器以查看更改。 – Baldrick
为了澄清,我用'with_touch'替换了'with_updated_at'。 – Baldrick