itx
itx

Reputation: 1409

Rails 5 field _type not generated in mongoid

I have class & subclass with one document looks like :

class Core::User
  include Mongoid::Document
  include Mongoid::Timestamps

  store_in collection: 'users'
end

class Core::Moderator < Core::User

end

I tried to add a user from console

2.4.2 :002 >  user = Core::User.new(email: '[email protected]', name: 'new user')
 => #<Core::User _id: BSON::ObjectId('5a015465fe37a86430b1e0ff'), created_at: nil, email: "[email protected]", name: "new_user", updated_at: nil> 
2.4.2 :003 > user.save
 => true 
2.4.2 :004 > user._type
NoMethodError: undefined method `_type' for #<Core::User:0x0000000003e77ea0>
    from (irb):4

And then add new moderator :

2.4.2 :005 > moderator = Core::Moderator.new(email: '[email protected]', name: 'new moderator')
#<Core::Moderator _id: BSON::ObjectId('5a015600fe37a86430b1e100'), created_at: nil, email: "[email protected]", name: "new moderator", updated_at: nil>
2.4.2 :006 > moderator.save
=> true 
2.4.2 :007 > moderator._type
=> "Core::Moderator"

Next add new user again :

2.4.2 :008 >  user = Core::User.new(email: '[email protected]', name: 'new user 2')
 => #<Core::User _id: BSON::ObjectId('5a015704fe37a86430b1e101'), created_at: nil, email: "[email protected]", name: "new user 2", updated_at: nil> 
2.4.2 :009 > user.save
 => true 
2.4.2 :010 > user._type
 => "Core::User"

Why I should create subclass first to get field _type on parent class? Every I start new console and create new user (Core::User) the field _type not generated.

I user Ruby 2.4.2, Rails 5.1.4, Mongoid 6.2.1

Upvotes: 1

Views: 350

Answers (1)

max
max

Reputation: 102001

In order for inheritance to work as expected in Mongoid you need to set preload_models: true. Otherwise the model cannot know that it has subclasses.

# config/mongoid.yml
development:
  # ...
  options: 
    # ...
    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    preload_models: true 

Upvotes: 1

Related Questions