ユーザーモデルに次のコード行があります。
attr_accessor :birthdate
同じモデルで、次のようにしてその誕生日を設定しようとするメソッドがあります。
self.birthdate = mydate
mydateはDateオブジェクトです。
このエラーが発生します:undefined method birthdate='
なぜこうなった?attr_accessorはセッターとゲッターを作成しませんか?
ユーザーモデルに次のコード行があります。
attr_accessor :birthdate
同じモデルで、次のようにしてその誕生日を設定しようとするメソッドがあります。
self.birthdate = mydate
mydateはDateオブジェクトです。
このエラーが発生します:undefined method birthdate='
なぜこうなった?attr_accessorはセッターとゲッターを作成しませんか?
推測させてください、あなたはクラスメソッドからそのセッターを呼び出していますよね?
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)