2
class User < ActiveRecord::Base
  attr_accessor :password

  Rails.logger.info "xxy From outside" 
  def before_create
      Rails.logger.info "xxy From inside the before_create" 
  end
end

当调用User.save控制器时,我的开发日志会被拾起,xxy From outside但不是xxy From inside the before_create这样我认为它已被弃用是正确的吗?

如果是这样,我如何在保存之前调用模型方法?或者按照xxy From outside记录,这是否意味着在保存模型实例时会自动调用所有方法?

4

3 回答 3

11

他们还在那里。你似乎做错了。这是正确的方法:

# Define callback:
before_create :method_name

# and then:
def method_name
  Rails.logger.info "I am rad"
end
于 2013-09-25T03:39:57.813 回答
0

They are still there. They just take a block instead of defining them as a method:

  Rails.logger.info "xxy From outside" 
  before_create do
    Rails.logger.info "xxy From inside the before_create" 
  end
于 2015-04-10T22:50:20.467 回答
0

不是我知道的。如ActiveModel::Callbacks源中所述,您可以通过覆盖 before_create 方法(为什么要这样做?)来获得您正在寻找的结果。

# First, extend ActiveModel::Callbacks from the class you are creating:
#
# class MyModel
# extend ActiveModel::Callbacks
# end
#
# Then define a list of methods that you want callbacks attached to:
#
# define_model_callbacks :create, :update
#
# This will provide all three standard callbacks (before, around and after)
# for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
# you need to wrap the methods you want callbacks on in a block so that the
# callbacks get a chance to fire:
#
# def create
# run_callbacks :create do
# # Your create action methods here
# end
# end
#
# Then in your class, you can use the +before_create+, +after_create+ and
# +around_create+ methods, just as you would in an Active Record module.
#
# before_create :action_before_create
#
# def action_before_create
# # Your code here
# end
于 2013-09-25T03:43:09.103 回答