Ruby DataMapper:未定义的方法`include?'

时间:2014-05-18 15:06:07

标签: ruby ruby-datamapper

我正在页面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>'

我做错了什么?感谢。

1 个答案:

答案 0 :(得分:1)

我从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! drop并向上重新创建存储库以匹配模型定义。因此,运行此方法以查看代码是否有效。

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