LoginSignup
1
1

More than 5 years have passed since last update.

ActiveModel::AttrbiuteMethodsが機能しない原因

Last updated at Posted at 2018-03-10

AttributeMethodsが正しく機能するためには、

attribute_method_prefix, attribute_method_suffixは
define_attribute_method 'age' の手前に書いておく必要があります。

公式チュートリアルのコード

class Person
  include ActiveModel::AttributeMethods

  attribute_method_prefix 'reset_'
  attribute_method_suffix '_highest?'
  define_attribute_methods 'age'

  attr_accessor :age

  private
    def reset_attribute(attribute)
      send("#{attribute}=", 0)
    end

    def attribute_highest?(attribute)
      send(attribute) > 100
    end
end

以下のようにちゃんと機能して動きます。

person = Person.new
person.age = 110
person.age_highest?
=> true
機能しないコード

class Person
  include ActiveModel::AttributeMethods

  define_attribute_methods 'age' #←  attribute_method_prefixの手前にに定義してしまっている
  attribute_method_prefix 'reset_'
  attribute_method_suffix '_highest?'


  attr_accessor :age

  private
    def reset_attribute(attribute)
      send("#{attribute}=", 0)
    end

    def attribute_highest?(attribute)
      send(attribute) > 100
    end
end

person = Person.new
person.age = 110
person.age_highest?
=> NoMethodError undefined_method 'age_highest?'

順番で影響をうけるので、公式コードの書き方は素直に真似した方がよさそうです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1