在父级上调用方法时,Rails NoMethodError

时间:2013-07-11 03:16:58

标签: ruby-on-rails ruby single-table-inheritance nomethoderror

在Rails 4中使用单表继承 hstore ,但在尝试调用父项中的方法时出错:

# models/item.rb
class Item < ActiveRecord::Base
  def getter_setter_for(key)
    define_method(key) do
      properties && properties[key]
    end

    define_method("#{key}=") do |value|
      self.properties = (properties || {}).merge(key => value)
    end
  end
end

# models/disk_item.rb
class DiskItem < Item
  %w[filename path].each do |key|
    getter_setter_for(key)               ##  <== error calling this method
  end
end

错误:

Exception encountered: #<NoMethodError: undefined method `getter_setter_for' for #<Class:0x007f8c739a5ae0>>

我忽略了哪些显而易见的事情?

1 个答案:

答案 0 :(得分:1)

getter_setter_for(key)是一个实例方法。但它在课堂上被称为。它将在类范围的DiskItem类加载期间调用。