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)
Written by shinn
Related protips
4 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#