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.
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.
.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
you can use after_create
instead of after_save
to avoid infinte loop occurred by update_attributes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With