如何重写Rails的模型一列? [英] How to override a column in Rails model?

查看:130
本文介绍了如何重写Rails的模型一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,我的数据库表之一。我希望覆盖列名称为特定的表。我将如何实现这一目标。

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.

例如,让我的表被称为模拟,它有一列名为 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.

推荐答案

可以实现通过的覆盖如文档中描述的默认访问。所有的列值可自动通过Active Record对象的基本访问,但有时你想专注这一行为。这可以通过覆盖默认的访问(使用相同的名称属性)并调用read_attribute(attr_name)和write_attribute(attr_name,值)真正改变的事情要做。

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) and write_attribute(attr_name, value) to actually change things.

滚动到重写默认的访问以了解更多信息。

Scroll to the Overwriting default accessors for more info.

这篇关于如何重写Rails的模型一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆