我有两种模式:
class MenuPosition
include Mongoid::Document
field :name, type: String
field :category, type: String
field :portion, type: Integer
field :carbo, type: Float
field :fat, type: Float
field :protein, type: Float
field :colesterol, type: Float
field :saturated_fats, type: Float
field :suger, type: Float
field :omega3, type: Float
field :omega6, type: Float
index :name, unique: true
validates_uniqueness_of :name
end
和
class Menu
include Mongoid::Document
field :assigned_date, type: Date
embeds_many :menu_position
index :assigned_date, unique: true
validates_uniqueness_of :assigned_date
def self.test
position = {
"name" => "pork",
"category" => "meal",
"portion" => 100,
"carbo" => 4,
"fat" => 2,
"protein" => 5,
"colesterol" => 1,
"saturated_fats" => 1
}
MenuPosition.safely.create!(position)
position = MenuPosition.find_by_name("pork")
p position
Menu.safely.create!(assigned_date: Date.new(2011, 04, 01))
menu = Menu.where(assigned_date: Date.new(2011, 04, 01)).entries[0]
p menu
menu.menu_position = [position]
menu.save
menu = Menu.where(assigned_date: Date.new(2011, 04, 01)).entries[0]
p menu
p menu.menu_position
return 0
end
我使用self.test方法测试嵌入文档:
it "test it" do
Menu.test.should eq(0)
end
当我运行测试时,我插入了MenuPosition和Menu,但未填充Menu.MenuPosition:
#<MenuPosition _id: 4f87f93e83b7e01e4800003e, _type: nil, name: "pork", category: "meal", portion: 100, carbo: 4.0, fat: 2.0, protein: 5.0, colesterol: 1.0, saturated_fats: 1.0, suger: nil, omega3: nil, omega6: nil>
#<Menu _id: 4f87f93e83b7e01e4800003f, _type: nil, assigned_date: 2011-04-01 00:00:00 UTC>
#<Menu _id: 4f87f93e83b7e01e4800003f, _type: nil, assigned_date: 2011-04-01 00:00:00 UTC>
[] // <- here is menu.menu_position
我该如何解决?
更新
我试过这个:
Menu.create(assigned_date: Date.new(2011, 04, 01))
menu = Menu.where(assigned_date: Date.new(2011, 04, 01)).entries[0]
menu.menu_position.create(position)
menu.save
menu = Menu.where(assigned_date: Date.new(2011, 04, 01)).entries[0]
p menu
p menu.menu_position
但它回归:
<Menu _id: 4f880f0a83b7e0194c00003e, _type: nil, assigned_date: 2011-04-01 00:00:00 UTC>
[]
更新2:
如果我将embedded_in :menu
添加到MenuPosition中,则会有效。但在这种情况下,我无法在没有菜单文档的情况下将MenuPosition文档存储在MongoDb中:(