where is after_update called twice?

2019-08-13 19:23发布

My model Projelement has these callbacks:

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

And Projelement.log_activity looks like:

# 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

So when a Projelement is created, all's good:

  • One Activity record of created type

But when a Projelement is updated, then I get:

  • Two duplicate Activity records of updated type
  • Same timestamps

Can after_update callback be called twice somewhere?

p.s. when a Projelement is saved, it looks something like this (a Milestone is a Projelement):

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

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-13 20:09

Thanks to @frederick-cheung and @pjumble:

In the update method, where Projelement instance is being updated:

  • update_attributes is being called
  • Then save is called

so the after_update callback is initiated twice per Projelement

查看更多
登录 后发表回答