Dar*_*ren 4 activerecord ruby-on-rails
我试图设置我自己的方法来覆盖数据库属性,以便我可以拦截数据库值为null的值.
Rails似乎允许我设置一个与数据库列同名的方法,但是我需要一种替代方法来访问数据库值以返回我想要的内容.
想象一下,我有一个数据库列"date",我想在数据库中为null时将其设置为其他内容.
我想设置一个方法如下
def date
if (alternative_db_value_object).date == nil
"Put this"
else
"Put that"
end
end
Run Code Online (Sandbox Code Playgroud)
或者,如果有人能提出更好的方法,我会非常感激.
..在'date'方法中,你可以使用
self[:date]
Run Code Online (Sandbox Code Playgroud)
要么
read_attribute(:date)
Run Code Online (Sandbox Code Playgroud)
更新:它似乎不再适用于rails 5.一个应该使用super:
def length=(minutes)
super(minutes.to_i * 60)
end
def length
super / 60
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1113 次 |
| 最近记录: |