Monday, May 23, 2011

[Rails] Execute after_save callback only if an attribute is modified

for instance if I want to fetch a url if the url attribute has
changed.

I know that I can use before_save and do:

def get_url
get_url if url_changed?
end

However, this is not really correct. If that call is using delayed job
or some other technique since the object is not yet saved in the
before_save callback, for instance.

def get_url
Queue.add(:fetch_url, id)
end

might end up getting the old URL if it is executed before the update
completes. The prior technique would also end up using the new URL if
the update fails. This is the sort of thing that should be done after
the object is updated.

I'd like to do something like:

after_save :get_url, :if => url_changed?

but this won't work because the url is no longer "dirty" after the
save.

Settings flags in the before_save and executing after_save gets ugly
real fast, and has potential for infinite loops, requiring hackery.

Is there a clean way to do this?

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate