2013-09-25 44 views
1
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,所以我认为它已被弃用?Rails 4中已经废弃了before_create和after_create方法吗?

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

+0

'User.save'可能是一个更新,在这种情况下'before_create'不会被调用。另外,检查pjammer的答案。 – Mischa

回答

11

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

# Define callback: 
before_create :method_name 

# and then: 
def method_name 
    Rails.logger.info "I am rad" 
end 
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 
0

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

Rails.logger.info "xxy From outside" 
    before_create do 
    Rails.logger.info "xxy From inside the before_create" 
    end 
相关问题