我在用户模型中有这行代码:
attr_accessor :birthdate
在同一个模型中,我有一个方法试图通过这样做来设置生日:
self.birthdate = mydate
其中mydate是Date对象。
我收到此错误:undefined method birthdate='
为什么会这样?不是attr_accessor会创建一个setter和一个getter吗?
答案 0 :(得分:18)
让我猜一下,你是从类方法中调用setter,对吧?
class Foo
attr_accessor :bar
def set_bar val
self.bar = val # `self` is an instance of Foo, it has `bar=` method
bar
end
def self.set_bar val
self.bar = val # here `self` is Foo class object, it does NOT have `bar=`
bar
end
end
f = Foo.new
f.set_bar 1 # => 1
Foo.set_bar 2 # =>
# ~> -:10:in `set_bar': undefined method `bar=' for Foo:Class (NoMethodError)