Putting Some Logic in Accessors That Get DB Field Data


#1

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.
removed_email_address@domain.invalid

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info


#2

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.


#3

Sexy! :slight_smile:

On 1/25/07, Jim L. removed_email_address@domain.invalid wrote:

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


John K.
removed_email_address@domain.invalid

http://www.kopanas.com
http://www.cusec.net
http://www.soen.info