Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails after_save infinite loop

I have a model which stores the details for retail outlets.

In Outlet model I have a before filter

after_save :is_outlet_verified

def is_outlet_verified
    if self.latitude.present? && self.longitude.present?
      self.update_attributes(:is_verified => true)
    else
      self.update_attributes(:is_verified => false)
    end
  end

I want to set is_verified field to true if outlet is geocoded. However when is_outlet_verified is successfully executed, it triggers after_save callback which again triggers is_outlet_verified.

like image 360
VivekVarade123 Avatar asked Mar 05 '14 11:03

VivekVarade123


3 Answers

Ideally you would do something like this in a before_save callback, not after_save - just set the is_verified attribute and then just let the save take place as normal.

If you really need to do this, you can use update_column instead of update_attribute, which will skip all callbacks.

One caveat to note - if a before_save callback returns false, then the save will not go ahead.

like image 145
sevenseacat Avatar answered Nov 02 '22 06:11

sevenseacat


.update_attributes invokes the .save method, so calling it after_save creates an infinite loop

I'd do it before_save, like this:

before_save :is_outlet_verified

  def is_outlet_verified
    if self.latitude.present? && self.longitude.present?
      self.is_verified = true
    else
      self.is_verified = false
    end
  end
like image 23
Richard Peck Avatar answered Nov 02 '22 08:11

Richard Peck


you can use after_create instead of after_save to avoid infinte loop occurred by update_attributes

like image 2
Rajarshi Das Avatar answered Nov 02 '22 07:11

Rajarshi Das