代码之家  ›  专栏  ›  技术社区  ›  Peter

在Rails中自定义ATTR读卡器

  •  3
  • Peter  · 技术社区  · 15 年前

    如果你写的话大部分都是在Rails上 my_obj.attr 它抬起头来 attr 在数据库中报告。如何创建自定义 def 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 回复  |  直到 15 年前
        1
  •  3
  •   alex.zherdev    15 年前

    就像这样:

    def attr
      value = read_attribute :attr
      value = modify(value)
      write_attribute :attr, value
      save
      value
    end
    
        2
  •  1
  •   Gdeglin    15 年前

    如果每次获取属性时都要将修改后的值保存回数据库,那么中微子的方法是好的。不建议这样做,因为每次尝试读取属性时,即使属性没有更改,它也会执行一个额外的数据库查询。

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

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