Rails Rails 开发中遇到的关于 after_create 的比较诡异的问题

chucai · August 14, 2012 · Last by qisine replied at August 20, 2012 · 3129 hits

情况是这样的 我在 model 的 before_create 中定义一个 after_create 方法,等到 model 保存成功后调用 实例代码如下

class A < ActiveRecord::Base
   before_create :method_a

   def method_a
      self.class.after_create do
         puts "calling method_a ........."
      end
   end
end

如上,会打印 5 次 calling method_a ......... 但是

class A < ActiveRecord::Base
   before_create :method_a


   def method_a
      self.class_eval <<-RUBY
        def method_b
           puts "calling method_a ........."
        end
        after_create :method_b
     RUBY
   end
end

只会打印 1 次 calling method_a ......... 大家遇到过这种情况么?

实际情况是,我在 rspec 测试中发现的

我估计情况是这样的,每次你 A.create,你就加一个 callback,因为 self.class.after_create 是累计的,不是取代你之前定义的 callbacks。除非此是你真正的目的,可能下面的方法更好点:

class A < ActiveRecord::Base before_create :method_a after_create :method_b

def method_a self.class_eval do def method_b; puts 'in method_b';end end end

private method_b;end end

You need to Sign in before reply, if you don't have an account, please Sign up first.