MongoMapper 嵌入式文档
我将产品作为类别类中的嵌入文档,如下所示:
require 'mongo_mapper'
class Category
include MongoMapper::Document
key :Name, String
key :NumberOfProducts, Integer
many :products
end
这是产品类:
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)
I have products as an embedded document inside the category class as shown below:
require 'mongo_mapper'
class Category
include MongoMapper::Document
key :Name, String
key :NumberOfProducts, Integer
many :products
end
and here is the Product class:
require 'mongo_mapper'
class Product
include MongoMapper::EmbeddedDocument
key :Name, String
end
I am using the following code to display the Products but it says no method "Name" found.
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
}
here is the error:
undefined method `Name' for {"Name"=>"Amiga"}:BSON::OrderedHash (NoMethodError)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,首先要尝试的是你有:
...但是然后你尝试使用
category.Products.each
访问它绝对保持你的命名一致,我建议使用 ruby 约定(下划线,不是驼峰式大小写,当然也不是非类的大写驼峰式大小写)。
所以,也许:
Well, first thing to try is that you have:
...but then you try to access it with
category.Products.each
Definitely keep your naming consistent, and I'd recommend using ruby conventions (underscored, not camel cased, and certainly not capitalized camel case for non-classes).
So, maybe:
您返回的对象就像哈希一样。为了访问名称,您需要使用
product["Name"]
或category["Name"]
。例如
The object you're getting back acts like a hash. In order to access the name you need to use
product["Name"]
orcategory["Name"]
.e.g.
在你的控制器
视图中
In your controller
View