在Rails 4中是否已弃用before_create和after_create方法?

时间:2013-09-25 03:17:58

标签: ruby-on-rails ruby-on-rails-4

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时,这是否意味着在保存模型实例时会自动调用所有方法?

3 个答案:

答案 0 :(得分:11)

They are still there.你好像做错了。这是正确的方法:

# Define callback:
before_create :method_name

# and then:
def method_name
  Rails.logger.info "I am rad"
end

答案 1 :(得分:0)

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

# 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

答案 2 :(得分:0)

他们还在那里。他们只是采取一个块而不是将它们定义为一种方法:

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