Prevent infinite loop when updating attributes within after_commit, :on => :create

后端 未结 3 1046
太阳男子
太阳男子 2020-12-20 15:02

I create an infinite callback loop when I need to update an attribute during an after_commit, :on => :create. It only occurs if I need to update an attribute

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 15:37

    You can use the method update_column that will skip all callbacks of your model:

    self.update_column(:filename, filename)
    

    Or you could use the method update_all, wich follows the same behavior

    self.class.where('id = ?', self.id).update_all(:filename => filename)
    

    And last but not least, my personal favorite:

    self.filename = filename
    self.send(:update_without_callbacks)
    

    This one makes it pretty clear that all callbacks are been ignored, what is very helpful


    Also, as a different alternative, you coud use after_create instead of after_commit if you want to run the generate method only when a new record is saved

提交回复
热议问题