我正在谈论的一个例子:
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_attribute
和 write_attribute
方法。我认为我在上面的例子中所做的事情一定有问题;否则,为什么他们会祝福这些方法作为重写属性方法的“正确方法”?他们还强制使用了一个更丑陋的习语,所以一定有一个充分的理由......
我真正的问题:这个例子有什么问题吗?
最佳答案
呼应 Gareth 的评论...您的代码将无法按编写的方式工作。应该这样重写:
def name=(name)
write_attribute(:name, name.capitalize)
end
def name
read_attribute(:name).downcase # No test for nil?
end
关于ruby-on-rails - 重写 ActiveRecord 属性方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/373731/