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

查看:22
本文介绍了覆盖 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 docs,它建议使用 read_attributewrite_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?

推荐答案

回应 Gareth 的评论...您的代码将无法正常工作.应该这样改写:

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天全站免登陆