覆盖的ActiveRecord属性的方法 [英] Override ActiveRecord attribute methods

查看:133
本文介绍了覆盖的ActiveRecord属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么我谈论的一个例子:

An example of what I'm talking about:

class Person < ActiveRecord::Base
  def name=(name)
    super(name.capitalize)
  end
  def name
    super().downcase  # not sure why you'd do this; this is just an example
  end
end

这似乎工作,但我只是读的 ActiveRecord的覆盖属性的方法:: Base的文档的部分,并建议使用 read_attribute write_attribute 的方法。我想一定有什么毛病我在做什么在上面的例子;否则,他们为什么会保佑这些方法是正确的方式来覆盖属性的方法?他们也迫使很多丑陋的成语,所以必须有一个很好的理由......

This seems to work, but I was just read the section on overriding attribute methods in the ActiveRecord::Base docs, and it suggests using the read_attribute and write_attribute methods. I thought there must be something wrong with what I'm doing in the example above; otherwise, why would they bless these methods as the "right way" to override attribute methods? They're also forcing a much uglier idiom, so there must be a good reason...

我真正的问题:有什么不对的例子

My real question: Is there something wrong with this example?

推荐答案

加雷斯赞同的意见......因为你写的code将无法正常工作。应该这样改写:

Echoing Gareth's comments... your code will not work as written. It should be rewritten this way:

def name=(name)
  write_attribute(:name, name.capitalize)
end

def name
  read_attribute(:name).downcase  # No test for nil?
end

这篇关于覆盖的ActiveRecord属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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