Rails:setter 中的 Attr 访问器未定义方法 [英] Rails: Attr accessor undefined method in the setter
本文介绍了Rails:setter 中的 Attr 访问器未定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在用户模型中有这行代码:
I have this line of code in a User model:
attr_accessor :birthdate
在同一个模型中,我有一个方法尝试通过这样做来设置生日:
In the same model, I have a method that tries to set that birthdate by doing this:
self.birthdate = mydate
其中 mydate 是一个 Date 对象.
Where mydate is a Date object.
我收到此错误:undefined methodbirthdate='
为什么会这样?attr_accessor 不是创建了 setter 和 getter 吗?
Why is this happening? Isn't attr_accessor creates a setter and a getter?
推荐答案
让我猜猜,你是从一个类方法中调用那个 setter,对吧?
Let me guess, you're calling that setter from a class method, right?
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)
这篇关于Rails:setter 中的 Attr 访问器未定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文