如何覆盖 Rails 模型中的列?
我有一个数据库表的模型。我想覆盖该特定表的列名。我将如何实现它。
例如,让我的表名为 DUMMY,它有一个名为 col_a
的列,
col_a
20
34
42
23
12
我将执行 @dummy.col_a
。现在,对于以 0 结尾的数字,此方法应该返回 0,对于其他所有内容,它应该返回原始值。我可以通过定义一个新方法来做到这一点,但我想覆盖列名本身。请帮忙。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以重写
col_a
方法。使用read_attribute
读取数据库中值的方法。像这样的东西:You can override the
col_a
method. Use theread_attribute
method to read the value in database. Something like this:您可以简单地定义一个与列同名的方法。要获取实际的列值,请使用 self[column_name]。所以像这样的东西应该可以工作:(
这假设 col_a 是一个整数。)
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.)
我来晚了一点,但一个非常优雅的方法是简单地使用
super
I'm a little late to the party here, but a really elegant way to do it is to simply use
super
您可以通过覆盖默认访问器(如文档中所述)来实现此目的。所有列值都可以通过 Active Record 对象上的基本访问器自动获得,但有时您希望专门化此行为。这可以通过覆盖默认访问器(使用与属性相同的名称)并调用 read_attribute(attr_name) 和 write_attribute(attr_name, value) 来实际更改内容来完成。
滚动到覆盖默认访问器部分以获取更多信息。
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.