在rails中自定义attr_reader

时间:2010-01-27 07:12:40

标签: ruby-on-rails

如果你写my_obj.attr,它主要在rails中,它在数据库中查找attr并报告回来。如何创建自定义def attr方法,在内部查询数据库attr,修改它并返回?换句话说,这里缺少的是什么:

# Within a model. Basic attr_reader method, will later modify the body.
def attr
  get_from_database :attr   # <-- how do I get the value of attr from the db?
end

2 个答案:

答案 0 :(得分:3)

类似的东西:

def attr
  value = read_attribute :attr
  value = modify(value)
  write_attribute :attr, value
  save
  value
end

答案 1 :(得分:1)

如果要在每次获取属性时将修改后的值保存回数据库,Neutrino的方法就很好。这不推荐,因为每次尝试读取属性时它都会执行额外的数据库查询,即使它没有更改。

如果您只想修改属性(例如将其大写),您可以执行以下操作:

 def attr
   return read_attribute(:attr).capitalize #(or whatever method you wish to apply to the value)
 end