Re: Using before_save to update a record only once.

MenDAKE
2007-03-05T22:20:17Z

Philip Hallstrom wrote:
>>> answer
>> that?
> Hrm... something like this assuming your model has
''completed''
> attribute.
>
> class MyModel < ...
>
>    attr :is_complete
>
>    def completed=(val)
>      if completed == 0 && val == 1 then
>        is_complete = true
>      else
>        is_complete = false
>      end
>      completed = val
>    end
>
>    def before_save
>      if is_complete != true then
>        return false
>      end
>      true
>    end
>
> end

Thanks, that makes sense. I implemented something similar to your
example, but for some reason the completed field now never gets saved.
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?