简体   繁体   English

是否在事务开始之前在Rails ActiveRecord中运行了一个回调?

[英]is there a callback which runs just before the transaction begins in rails ActiveRecord?

I just want to manipulate a model level object when it is newly created or it is updated. 我只想在新创建或更新模型级对象时对其进行操作。 For example, consider there is a test table with name attribute: 例如,考虑有一个具有名称属性的测试表:

class Test < ActiveRecord::Base
  custom_callback :hi
  def hi
    name = "h"
  end
end
m = Test.new(:name => "hello")
m.save

I just want to write a custom callback which should get executed before_validation and should get executed whenever a save or save! 我只想编写一个自定义回调,该回调应在before_validation之前执行,并且每次保存或保存时都应执行! is called. 叫做。 Ideally, I want some callback in rails 2.3 which should get executed and hook into ActiveRecord::Base. 理想情况下,我希望在Rails 2.3中执行一些回调,然后将其执行并挂接到ActiveRecord :: Base中。 is there any gem to do this or does anyone know how to write a callback which get executed before 'before_validation' callback? 有没有做这件事的宝石,或者没有人知道如何编写在“ before_validation”回调之前执行的回调吗?

You could override the save and save! 您可以覆盖savesave! methods to effectively inject the code. 有效注入代码的方法。 There's also the initialize method that might be appropriate depending on what you're trying to do. 根据您要尝试执行的操作,还可能存在合适的initialize方法。 Also, before_validation runs before validate , so how much earlier do you need it to run exactly, and why? 另外, before_validationvalidate之前运行,那么您需要多before_validation才能完全运行它?为什么?

Can you say more about why you want to do this? 您能否说说为什么要这样做? It sounds like you may have a design problem and you're trying to find a hack instead of addressing a more fundamental issue. 听起来您可能有一个设计问题,并且您正试图找到一个技巧,而不是解决一个更基本的问题。

It seems you are looking for before_save, which runs after validation: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 似乎您正在寻找的before_save,它将在验证后运行: http : //api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Please refer to This answer 请参考这个答案

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

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