保存对象时after_save如何工作

SSP*_*SSP 15 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

如果我执行以下操作:

@user.name = "John"    
@user.url = "www.john.com"
@user.save
Run Code Online (Sandbox Code Playgroud)

如果我使用 after_save

@user.url = "www.johnseena.com"
@user.save
Run Code Online (Sandbox Code Playgroud)

我这样做会发生什么?

我认为它应该保存值,因为'after_save'回调.

Sam*_*ron 34

在我看来,如果你saveafter_save回调函数中调用函数,那么它将陷入递归,除非你在开头放一个警卫.像这样

class User < AR::Base
      after_save :change_url

      def change_url
          #Check some condition to skip saving
          url = "www.johnseena.com"
          save              #<======= this save will fire the after_save again
      end
end
Run Code Online (Sandbox Code Playgroud)

然而,除了把一个后卫,你可以使用update_column

def change_url
    update_column(:url, "www.johnseena.com")
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它不会开火after_save.但是,它会开火after_update.所以,如果你对该回调有任何更新操作,那么你再次进行递归:)

  • 注意:实际上,“#update_column”会[跳过回调](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_columns)。 (2认同)

pra*_*ase 7

after_save的回调将被触发不论其一个保存更新该对象上.

也,

update_column不会触发任何回调(即after_update)并跳过验证.请参阅http://apidock.com/rails/ActiveRecord/Persistence/update_column

U应特别使用after_createafter_update,具体取决于操作及其时间.

after_create :send_mail
def send_x_mail
  #some mail that user has been created
end

after_update :send_y_mail
def send_y_mail
  #some data has been updated
end

after_save :update_some_date
def update_some_data
  ...
  action which doesnt update the current object else will trigger the call_back
end
Run Code Online (Sandbox Code Playgroud)

另请参阅`after_create`和`after_save`之间有什么区别以及何时使用哪个?对于回调,请参阅http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M000059