MongoMapper Embedded Documents
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 pr开发者_StackOverflowoduct.Name}
end
}
here is the error:
undefined method `Name' for {"Name"=>"Amiga"}:BSON::OrderedHash (NoMethodError)
Well, first thing to try is that you have:
many :products
...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:
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
The object you're getting back acts like a hash. In order to access the name you need to use product["Name"]
or 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"
In your controller
@categories = Category.all
View
<% @categories.products.each do |product| %>
<%= product.Name %> <br/>
<% end %>
精彩评论