I have a model for one of my database tables. I want to override the column name for that particular table. How would I achieve it.
For example, let my table be called DUMMY and it has one column called col_a
col_a
20
34
42
23
12
I would be doing a @dummy.col_a
. Now this method should return me 0 for numbers ending with 0 and for everything else, it should return the original value. I could do that by defining a new method, but I want to override the column name itself. Please help.
You can achieve that by overwriting default accessors as described in the documentation. All column values are automatically available through basic accessors on the Active Record object, but sometimes you want to specialize this behavior. This can be done by overwriting the default accessors (using the same name as the attribute) and calling
read_attribute(attr_name)
andwrite_attribute(attr_name, value)
to actually change things.Scroll to the Overwriting default accessors section for more info.
I'm a little late to the party here, but a really elegant way to do it is to simply use
super
You can simply define a method of the same name as the column. To get the actual column value, use self[column_name]. So something like this should work:
(This assumes col_a is an integer.)
You can override the
col_a
method. Use theread_attribute
method to read the value in database. Something like this: