当一个类的计数返回0时,文档如何声明它是持久的?

时间:2012-10-19 19:35:58

标签: mongodb mongoid

foo.persisted? == true时,文件如何声明foo.class.count == 0? 更重要的是,如何让文档真正持久化?

更新:从控制器调用Mongo::Foo.create()会增加计数。这是预料之中的。在单独的模块/类中调用createnewsave增加计数。

更新:我尝试将new / save次来电更改为create

更新:我还尝试了@foo_class.with(collection: "mongo_foos").create

[42] pry(#<FoosController>)> foo.class
=> Mongo::Foo
[43] pry(#<FoosController>)> foo.persisted?
=> true
[44] pry(#<FoosController>)> Mongo::Foo.count
=> 0
[47] pry(#<FoosController>)> foo.id
=> "5081a1a786ddc8e035000021"
[48] pry(#<FoosController>)> foo
=> #<Mongo::Foo _id: 5081a1a786ddc8e035000021, _type: nil, foo_daddy_id: nil, old_foo_daddy_id: 219, member_id: "F008AR", unix_time: nil, date_time: 2012-10-19 13:50:54 UTC, submitted: nil, json: nil>

以下是文档类的定义方式:

module Mongo
  class Foo
    include Mongoid::Document

    field :foo_daddy_id
    field :old_foo_daddy_id, type: Integer
    field :member_id,  type: String
    field :unix_time,  type: Integer
    field :date_time,  type: DateTime
    field :submitted,  type: Integer
    field :json,       type: Hash

    belongs_to :foo_daddy, class_name: "Mongo::FooDaddy"
    embeds_many :foo_dumplings, class_name: "Mongo::FooDumpling"

  end
end

正在使用foo.new(params); foo.save创建文档:

module FooThingy
  module Foo
    class Create < ::FooThingy::Base

      def initialize(options)
        # Sets instance variables used below
      end

      def execute!
        @foo = @foo_class.new({
          date_time: DateTime.strptime(@params["submitted_timestamp"], "%m-%d-%Y %H:%M:%S"),
          member_id: (@params[:member_id].present? ? @params[:member_id] : nil),
          old_foo_daddy_id: @params[:old_foo_daddy_id]
        })

        embed_foo_dumplings

        if @foo.save
          return FooThingy::Result.new(success: true, data: { foo: @foo })
        else
          return FooThingy::Result.new(success: false, data: { foo: @foo })
        end
      end

      private
      def embed_foo_dumplings
        # Embeds foo_dumplings
      end

    end
  end
end

这是我调用该模块来创建文档的地方:

class FoosController < ApplicationController
  def create
    foo_creator = FooThingy::Foo::Create.new(params: params, foo_class: Mongo::Foo)
    foo = foo_creator.execute!
    foo = foo.data[:foo]
    binding.pry
  end
end

1 个答案:

答案 0 :(得分:0)

我认为这个问题并不像看上去那么有趣。我修改了我的config/mongoid.yml以指定一个新数据库,一切都按预期运行。问题可能是由于32位MongoDB安装的限制。