Aaron Miler
Aaron Miler

Reputation: 889

Mongoid namespaced model, without namespace in database

I'm wondering if there is some way to ignore a models namespace with Mongoid. I'm moving all of my models to a rails engine, and name spacing them. I have been able to add them to the rails engine without the namespace and it references fine, but we are working on moving to a service oriented architecture and I would like to namespace all the models.

Here is an example model before and after

# Before
class Model
  include Mongoid::Document
  field :field1
end

# After
module Engine
  class Model
    include Mongoid::Document
    field :field1
  end
end

Here is what happens in the console when I do Engine::Model.all

=> #<Mongoid::Criteria
   selector: {}
   options:  {}
   class:    Engine::Model
   embedded: false>

If I could just make it so that mongoid looks for just Model it would like up with my data perfectly.

Ideally I'd be able to do Engine::Model.all and it would return this

=> #<Mongoid::Criteria
   selector: {}
   options:  {}
   class:    Model
   embedded: false>

Is there any way to accomplish this?

Upvotes: 2

Views: 776

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176482

Quoting the documentation:

The collection for the model's documents can be changed at the class level if you would like them persisted elsewhere. You can also change the database and session the model gets persisted in from the defaults.

Applied to your case

module Engine
  class Model
    include Mongoid::Document
    store_in collection: "models"
    field :field1
  end
end

The class cannot change, it must be Engine::Model because this is where the model is defined.

Upvotes: 5

Related Questions