如何在mongoid中的现有父文档中创建新的嵌入文档?

时间:2012-05-30 05:47:23

标签: ruby-on-rails mongoid

我正在尝试从父文档中删除嵌入的文档,然后添加另一个嵌入的文档但我收到错误。我的语法不正确吗?

错误

NoMethodError: undefined method `create' for []:Array

代码

u = User.last
u.classes.destroy_all
u.classes.create(:name => "Philsophy") # I get the error right at this line

Ruby on Rails 3.0.3
Mongoid 2.0.0.beta.20

谢谢!

2 个答案:

答案 0 :(得分:0)

关系方法 classes 返回一个Array,而不是您的基类。 要创建和嵌入对象,您需要在类上调用 new 方法, 然后将其附加到

这是一个可能与您的意图接近的工作示例。希望它能帮助你继续前进。

class User
  include Mongoid::Document
  field :name, type: String
  embeds_many :classes, class_name: 'MyClass'
end

class MyClass
  include Mongoid::Document
  field :name, type: String
  embedded_in :user
end

测试/单元/ user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    User.delete_all
  end

  test "embedded doc" do
    User.create(name: 'Gary')
    assert_equal(1, User.count)
    u = User.last
    u.classes.destroy_all
    puts "u.classes.class: #{u.classes.class}"
    u.classes << MyClass.new(:name => 'Philosophy')
    user = User.find(u.id)
    assert_equal('Philosophy', user.classes.first.name)
    puts user.to_json
  end
end

测试输出

Run options: --name=test_embedded_doc

# Running tests:

u.classes.class: Array
{"_id":"4fc62aeb7f11baa5b0000001","classes":[{"_id":"4fc62aeb7f11baa5b0000002","name":"Philosophy"}],"name":"Gary"}
.

Finished tests in 0.009929s, 100.7151 tests/s, 201.4302 assertions/s.

1 tests, 2 assertions, 0 failures, 0 errors, 0 skips

答案 1 :(得分:0)

https://mongoid.github.io/old/en/mongoid/v3/relations.html#embeds_many

很有帮助,并指出了许多可以将新对象添加到现有对象的方法,例如:

band.albums.build(name: "Violator")
band.albums.new(name: "Violator")

如果你有多个对象

band.albums.concat(
  Album.new(name: "Violator"),
  Album.new(name: "101")
)