如何覆盖 Rails 模型中的列? [英] 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.
例如,让我的表名为 DUMMY,它有一列名为 col_a
For example, let my table be called DUMMY and it has one column called col_a
col_a
20
34
42
23
12
我会做一个@dummy.col_a
.现在,对于以 0 结尾的数字,此方法应该返回 0,对于其他所有内容,它应该返回原始值.我可以通过定义一个新方法来做到这一点,但我想覆盖列名本身.请帮忙.
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.
推荐答案
您可以覆盖 col_a
方法.使用 read_attribute
方法读取数据库中的值.像这样:
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
这篇关于如何覆盖 Rails 模型中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!