2012-03-31 116 views
1

我的模型Projelement有這些回調:after_update被調用兩次?

after_create { |p| p.log_activity "created" } 
after_update { |p| p.log_activity "updated" } 

而且Projelement.log_activity樣子:

# create new Activity object 
# point it to the project & projelement 
@a = Activity.new 
@a.projelement = self 
@a.project = self.project 

# record the type of activity 
case op_type 
when "created" 
    @a.operation = "created" 
when "deleted" 
    @a.operation = "deleted" 
when "updated" 
    @a.operation = "updated" 
end 

@a.save 

所以當創建Projelement,所有的好:

  • 一個Activity記錄created

但當Projelement更新,然後我得到:

  • 兩個重複Activity記錄updated
  • 相同時間戳

可以after_update回調某處被調用兩次?

p.s.當保存一個Projelement,它看起來是這樣的(一個MilestoneProjelement):

def update  
    @milestone = Milestone.find(params[:id]) 

    respond_to do |format| 
    if @milestone.update_attributes(params[:milestone]) 

    # flag that current_user has this milestone 
    @milestone.read_by.clear 
    @milestone.read_by << current_user 
    @milestone.save 

    ... 
    end 
    end 
end 
+0

愚蠢的問題發起了兩次:你保存Projelement兩次?更新代碼是什麼樣的? – 2012-03-31 22:19:14

+0

愚蠢的初始職位:抱歉,我忘記發佈更新代碼。嗯,我以爲我沒有儲蓄兩次(長期看這個)。但粘貼代碼...我似乎調用''update_attributes''然後''save''? – 2012-03-31 22:31:16

+0

因爲您真的回答了您自己的問題,所以將其作爲評論發佈。是的,這是因爲你調用['update_attributes'](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L192)(內部調用'save')然後你自己再次調用'save'。 – pjumble 2012-03-31 22:35:51

回答

2

感謝@馮祥及@pjumble:

update方法,其中Projelement實例是更新:

  • update_attributes被稱爲
  • 然後save被稱爲

所以after_update回調每Projelement