Last Updated: February 25, 2016
· shinn

Polymorphic-embedded-associations in Mongoid

Mongoid is a MongoDB ORM written in Ruby and for Ruby applications, included Ruby on Rails.

Recently I've come across to use polymorphism in Mongoid. However I don't find some useful information on how to create/call a polymorphic object in the official documentation, only declaration. Here I'm going to show some examples on how to create and use polymorphism in embedded objects.

class Vehicle
  include Mongoid::Document
  embeds_many :vehicles, as: :moveable

  field :speed, type: Integer
  field :auto_pilot, type: Boolean
  field :name, type: String

class Car < Vehicle
  embedded_in :moveable, polymorphic: true

class Bike < Vehicle
  embedded_in :moveable, polymorphic: true

>> vehicle = Vehicle.new

>> vehicle.vehicles.create({speed: 180, auto_pilot: false, name: "car1"}, Car)

>> vehicle.vehicles.create({speed: 160, auto_pilot: false, name: "bike1"}, Bike)

4 Responses
Add your response


Hi, where Vehicle class?

over 1 year ago ·

Thanks for pointing out, I've updated the code snippet. Sorry for the confusing.

Happy coding :)

over 1 year ago ·

And Mine if we include vehicle Mongoid :: Document, there is no need to include Mongoid :: Document classes in Car and Bike.

But I'm not sure. :)

over 1 year ago ·

Yes you're right :)

over 1 year ago ·