MongoMapper嵌入式文档

时间:2010-07-19 17:26:12

标签: ruby mongomapper

我将产品作为类别类中的嵌入文档,如下所示:

require 'mongo_mapper'

class Category

include MongoMapper::Document

key :Name, String
key :NumberOfProducts, Integer
many :products

end

这是Product类:

require 'mongo_mapper'

class Product

include MongoMapper::EmbeddedDocument

  key :Name, String

end

我使用以下代码显示产品,但它说没有找到“名称”方法。

require 'rubygems'
require 'mongo'
require 'mongo_mapper'
require 'category'
require 'product'

include Mongo

MongoMapper.database = 'Northwind'

categories = Category.all()

categories.each{|category| puts category.Name

  unless category.Products.nil?

     category.Products.each{|product| puts product.Name}

  end


}

这是错误:

 undefined method `Name' for {"Name"=>"Amiga"}:BSON::OrderedHash (NoMethodError)

2 个答案:

答案 0 :(得分:2)

嗯,首先要尝试的是:

many :products

...但是您尝试使用category.Products.each

访问它

绝对保持你的命名一致,我建议使用ruby约定(强调,不是驼峰,非当然不是大写的驼峰)。

所以,也许:

class Category
  include MongoMapper::Document
  key :name, String
  many :products
end

class Product
  include MongoMapper::EmbeddedDocument
  key :name, String
end


categories = Category.all
categories.each do |category|
  puts category.name
  category.products.each do |product|
    puts "  " + product.name
  end
end

答案 1 :(得分:0)

你要回来的对象就像一个哈希。要访问该名称,您需要使用product["Name"]category["Name"]

e.g。

irb(main):007:0> oh.baz
NoMethodError: undefined method `baz' for {"foobar"=>"baz"}:BSON::OrderedHash
    from (irb):7
irb(main):008:0> oh[:foobar]
=> "baz"