Ruby DataMapper:未定义的方法"include?



我正在尝试页面上的一个例子http://ruby.about.com/od/sinatra/a/datamapper.htm。我从网站上复制了以下代码:

require 'rubygems'
require 'dm-core'
require 'dm-migrations'
DataMapper.setup(:default, "sqlite3:///tmp/test1.db")
class Person
  include DataMapper::Resource
  property :firstname, String
  property :lastname, String
  property :email, String, :key => true
end
p = Person.new
p.attributes = {
  :firstname => 'John',
  :lastname => 'Doe',
  :email => 'john.doe@email.com'
}

通过ruby test.rb运行此代码,我得到一个错误消息

/usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0/gems/dm-core-1.2.1/lib/dm-core/resource.rb:335:in `block in attributes=': undefined method `include?' for nil:NilClass (NoMethodError)
    from /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0/gems/dm-core-1.2.1/lib/dm-core/resource.rb:332:in `each'
    from /usr/local/Cellar/ruby/2.0.0-p247/lib/ruby/gems/2.0.0/gems/dm-core-1.2.1/lib/dm-core/resource.rb:332:in `attributes='
    from test.rb:16:in `<main>'

我做错了什么?谢谢。

我从dm-core / lib / dm-core / resource.rb中找到了下面的代码。

# Assign values to multiple attributes in one call (mass assignment)
#
# @param [Hash] attributes
#   names and values of attributes to assign
#
# @return [Hash]
#   names and values of attributes assigned
#
# @api public
def attributes=(attributes)
  model = self.model
  attributes.each do |name, value|
    case name
    when String, Symbol
      if model.allowed_writer_methods.include?(setter = "#{name}=")
        __send__(setter, value)
      else
        raise ArgumentError, "The attribute '#{name}' is not accessible in #{model}"
      end
    when Associations::Relationship, Property
      self.persistence_state = persistence_state.set(name, value)
    end
  end
end

allowed_writer_methods为未设置的读取器。不将变量@allowed_writer_methods设置为可能有以下几个原因:可以在#attributes= 中批量分配的写入器方法列表。出于这些原因,您可能不会运行auto_migrate!来删除并向上重新创建存储库以匹配模型定义。因此,运行这个方法,看看你的代码是否工作。

关于错误,是的,它来自model.allowed_writer_methods.include?(setter = "#{name}=")行,由于上述原因,allowed_writer_methods给出nil, Nilclass#include?方法不存在。这就是(NoMethodError)明显的原因。

最新更新