Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a column in Rails model?

Tags:

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.

like image 474
bragboy Avatar asked May 06 '11 09:05

bragboy


1 Answers

You can override the col_a method. Use the read_attribute method to read the value in database. Something like this:

def col_a
  if self.read_attribute(:col_a).to_s.end_with?('0')
    0
  else
    self.read_attribute(:col_a)
  end
end
like image 170
htanata Avatar answered Sep 21 '22 23:09

htanata