Re: Using before_save to update a record only once.

Philip Hallstrom
2007-03-05T22:41:35Z

> 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

Ah, I suspect this is it... do something like...

self[''completed''] = val

or whatever rails does by default for this thing...

>>    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?
>
> --
> Posted via http://www.ruby-forum.com/.
>
> >