我有两个模型:
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 中:(