Putting Some Logic in Accessors That Get DB Field Data

Wow… I have no clue how to explain this. Excuse my vocabulary.

Their is one field in my DB that I want to test if it is null before
someone accesses it and if it is null return zero. How to I overwrite
the accessor for a field in my model so that I can test the value
being returned and if it is null return zero, otherwise return what
the value is?

Why am I doing this? Because unfortunately the data I am accessing is
from legacy systems so I can’t make sure that all the information has
been cleaned up before hand! Plus the bozzo who is writing the tool
to populate my DB from legacy systems refuses to clean data before he
puts it into my DB! Garbage in… garbage out! :slight_smile:

Am I making sense? How would I better describe what I am trying to do?

Thanks peeps :slight_smile:

John


John K.
[email protected]

http://www.kopanas.com

http://www.soen.info

Their is one field in my DB that I want to test if it is null before
someone accesses it and if it is null return zero. How to I overwrite
the accessor for a field in my model so that I can test the value
being returned and if it is null return zero, otherwise return what
the value is?

In your model, create a method with the same name as the attribute.
This overwrites the automagical one made by AR.

def my_attr
if @my_attr.nil?
0
else
@my_attr
end
end

@my_attr is still populated by Active Record, but you’re now
controlling what happens when it’s retrieved outside the model.

You can also overwrite the assignment by making a method like

def my_attr=(value)
if value.nil?
@my_attr = 0
else
@my_attr = value
end
end

The equal sign in the method definition denotes it’s the method for
assignment.

Sexy! :slight_smile:

On 1/25/07, Jim L. [email protected] wrote:

def my_attr
You can also overwrite the assignment by making a method like


John K.
[email protected]

http://www.kopanas.com

http://www.soen.info