Re: Using before_save to update a record only once.

Jean-François Trân
2007-03-05T22:34:39Z

MenDAKE :
> My code looks something like this:
>
> class MyModel < ActiveRecord::Base
>   attr :completed_is_changed
>
>   # This checks to see if the completed fiel was set to true for the
> first time.
>   def completed=(val)
>     if completed == 0 && val == 1
>       completed_is_changed = true
>     else
>       completed_is_changed = false
>     end
>
>     completed = val
>   end
>
>   def before_save
>     if completed_is_changed == true
>        #perform the action.
>     end
> end
>
> The actions are performed, but the completed field value is
> now never saved to the database. I would expect that the
> line "completed = val" would take care of that, but it
doesn''t
> seem to. Is something missing?

You can write it like that :

def completed=(val)
  completed_is_changed = completed == 0 && val == 1
  write_attribute(:completed, val)
end

   -- Jean-François.

--
Ruby ( http://www.rubyfrance.org ) on Rails ( http://www.railsfrance.org )

--~--~---------~--~----~------------~-------~--~----~
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-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com