Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

ruby - How to override a column in Rails model?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...