Test is a specific field is modified

Hello everybody

I’m relatively new to RoR but I find it really interesting. I’ve managed
to do lots of nice things bt I’m stuck with a specific problem.

I’ve got a table with 5 columns and among it one is a boolean and one is
a date. There are other fields (text fields…)
i’ve linked a checkbox to the boolean. I’ve managed to have the date set
at Time.now whenever I update the record.
But what I’d really like to do is to update the date field only when the
boolean is modified (and not when the user modifies some of the other
fields)

Can anyone help ?

Thanks

Martin

On 3/28/07, Martin Da silva [email protected] wrote:

But what I’d really like to do is to update the date field only when the
Posted via http://www.ruby-forum.com/.

Hey Martin,

There are a couple ways you can do this. The first is to write a
custom setter method for the boolean value:

class Foo < ActiveRecord::Base
def bool_field=(b)
self.date_field = Time.now
write_attribute :bool_field, b
end
end

The other way is to use an Observer.

class FooObserver < ActiveRecord::Observer
def before_update(foo)
old_foo = Foo.find foo.id
foo.date_field = Time.now if foo.bool_field != old_foo.bool_field
end
end

or you could put it directly in the Foo class…

class Foo < ActiveRecord::Base
before_update :update_time

def update_time
old_foo = Foo.find id
self.date_field = Time.now if self.bool_field != old_foo.bool_field
end
end

Now that I’ve written them all out, I think the last solution would be
best :slight_smile: I would use the middle solution if I had lots of stuff to do
when a record was modified.

Pat

On 3/28/07, Pat M. [email protected] wrote:

or you could put it directly in the Foo class…

class Foo < ActiveRecord::Base
before_update :update_time

def update_time
old_foo = Foo.find id
self.date_field = Time.now if self.bool_field != old_foo.bool_field
end
end

I think you would have to add a
return true

at the end of that method, because otherwise Rails will think that
some validation failed and it won’t save the record. I’m not 100%
sure though.

Pat

Pat M. wrote:

On 3/28/07, Pat M. [email protected] wrote:

or you could put it directly in the Foo class…

class Foo < ActiveRecord::Base
before_update :update_time

def update_time
old_foo = Foo.find id
self.date_field = Time.now if self.bool_field != old_foo.bool_field
end
end

I think you would have to add a
return true

at the end of that method, because otherwise Rails will think that
some validation failed and it won’t save the record. I’m not 100%
sure though.

Pat

Well this solution seems to work pretty well. Thanks a lot :slight_smile: