w6iyeg
Last Updated: February 25, 2016
·
5.049K
· 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
end

class Car < Vehicle
  embedded_in :moveable, polymorphic: true
end

class Bike < Vehicle
  embedded_in :moveable, polymorphic: true
end

>> 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

11231

Hi, where Vehicle class?

over 1 year ago ·
11306

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

Happy coding :)

over 1 year ago ·
11311

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 ·
11333

Yes you're right :)

over 1 year ago ·