Re: Using before_save to update a record only once.

Philip Hallstrom
2007-02-28T21:01:04Z

> I''d like to use before_save to perform an action (I won''t
get into the
> details), but only the first time the record is changed from 0 to 1.
> Here''s the code I have so far in my model:
>
> def before_save
>   if completed == 1
>      # perform the action
>   end
> end
>
> What the above does is perform the action when "completed" is set
to
> one, but the problem is I don''t want this to happen every single
time
> there is a save. So what I''d like to be able to do is check the
previous
> value of "completed" and only perform the action if it used to be
0 and
> is now 1. For example (psuedo code):
>
> def before_save
>   if old_completed == 0 and completed == 1
>      # perform the action
>   end
> end
>
> How would I go about this? Obviously, I could add code outside the
> model, but before_save seems like the nicest, cleanest place to for this
> code to be. I searched this forum and found a post that kind of helps
> answer my question, but it''s not super clear and I''m
still not sure what
> the best solution is. It sounds like I have to do an external find just
> to do this check, and that just doesn''t seem right to me. Is that
really
> the only way?

Don''t have a specific answer for you, but the acts_as_changed plugin
might come in handy for you...

http://agilewebdevelopment.com/plugins/acts_as_changed

-philip