2013-09-25 3 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, так что я был бы я прав, полагая, что это было устаревшим?Не устарели ли методы before_create и after_create в Rails 4?

Если да, то как я могу вызвать метод модели перед сохранением? Или был зарегистрирован как 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 
Смежные вопросы