2013-09-25 67 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 
相關問題