1

拥有以下工厂:

FactoryGirl.define do
  factory :user do
    provider "github"
    sequence(:uid) {|n| "111111#{n}"}
    sequence(:name) {|n| "name#{n}"}
    sequence(:email) {|n| "name#{n}@example.com"}
    sequence(:nickname) {|n| "nick#{n}"}
    sequence(:token) {|n| "111111111111111111111111111111111111111#{n}"}
    watchlists { [ FactoryGirl.build(:watchlist) ] }
  end
  factory :watchlist do
      sequence(:html_url) {|n| "https://github.com/user#{n}/repo#{n}"}
      description "One repo description"
      sequence(:forks) {|n| "1#{n}"}
      sequence(:watchers) {|n| "#{n}"}
      created_at "2012-11-21 00:09:12 UTC"
      pushed_at "2010-04-15 21:11:51 UTC"
      avatar_url "https://avatar.example.com/avatar.png"
  end
end

当我创建工厂时,如下所示:

let(:user) { FactoryGirl.create :user }

它导致 :user 仅持久化模型,没有嵌入的子模型 :watchlist :

1.9.3p194 :014 > User.all.entries
  MOPED: 10.8.0.6:27017 COMMAND      database=admin command={:ismaster=>1} (328.6924ms)
  MOPED: 192.168.3.101:27017 COMMAND      database=admin command={:ismaster=>1} (216.3296ms)
  MOPED: 127.0.0.1:27017 COMMAND      database=admin command={:ismaster=>1} (422.3838ms)
  MOPED: 127.0.0.1:27017 QUERY        database=mongoid_test collection=users selector={} flags=[:slave_ok] limit=0 skip=0 batch_size=nil fields=nil (354.1191ms)
 => [#<User _id: 51126ae3aaa0786654000001, _type: nil, created_at: 2013-02-06 14:38:27 UTC, updated_at: 2013-02-06 14:38:27 UTC, email: "name1@example.com", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, provider: "github", uid: "1111111", name: "name1", nickname: "nick1", token: "1111111111111111111111111111111111111111", secret: nil, user_hash: nil>] 
1.9.3p194 :015 > 

我怎样才能让嵌入式 mongoid 模型也持续存在?

4

1 回答 1

1

它应该是持久的,但您需要查询关系。

尝试:

User.first.watchlists

或者在 MongoDB shell 中,整个文档会像你期望的那样打印出来 db.users.find().pretty();

有关 MongoDB shell 的更多信息:http: //docs.mongodb.org/manual/mongo/

于 2013-02-07T03:01:03.340 回答