10

如果我做了以下內容:如何保存after_save的工作,當一個對象

@user.name = "John"  
@user.url = "www.john.com" 
@user.save 

如果我使用after_save

@user.url = "www.johnseena.com" 
@user.save 

我這樣做的時候會發生什麼?

我相信它應該因'after_save'回調而保存價值。

+0

你真的在''after_save'回調中使用實例變量'@ user'嗎? – Samiron

+2

你真的必須努力解釋你需要更好一點,並給出更多你嘗試過的例子。 – simonmorley

回答

27

在我看來,如果你在after_save回調函數中調用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 

然而,除了把一個後衛,你可以使用update_column

def change_url 
    update_column(:url, "www.johnseena.com") 
end 

在這種情況下,將不會觸發after_save。但是,它會觸發after_update。所以,如果您有任何更新操作上再打那麼你在遞歸再次:)

+0

偉大的方式來解釋感謝您的時間。 – SSP

+1

注意:'#update_column'實際上[跳過回調](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_columns)。 – jibiel

4

如果修改任何內容int after_save它將不會被保存,因爲save已經發生。介入的唯一機會是回滾整個交易。如果在after_save中添加另一個save,那麼它將是一個無限循環。

6

after_save的回調函數會被觸發,不論它是一個保存或對象上的更新

此外,

update_column不會觸發任何回調(即after_update)和太跳過驗證。見http://apidock.com/rails/ActiveRecord/Persistence/update_column

ü應該明確使用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 

另見What is the difference between `after_create` and `after_save` and when to use which?和回調見http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M000059

+0

'after_update'和'before_update'都是作爲rails 4.1存在的。您可以從[Rails指南]中檢查可用回調的完整列表(http://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks) –

1

而不是執行兩個查詢的數據庫,並擔心遞歸的,你可能要考慮只是修改數據的有效載荷它關係到服務器之前。

class User < AR::Base 
     before_save :change_url 

     def change_url 
      url = "www.johnseena.com" 
     end 
end 
0

非常感謝所有幫助過我的人。這是解決我的問題的解決方案。我被訂單模型修改如下:

class Order < ActiveRecord::Base 

    has_and_belongs_to_many :users 

    validates :item, presence: true 

    def add_order(username, order) 
    user = User.where(username: username).first 
    if !user.nil? 
     user.orders.create(item: order.item) 
    end 
    end 

    def remove_order(order) 
    end 

end 
相關問題