June 28, 2012
Polymorphic and STI models working together in Mongoid

Here is an example of polymorphic and STI models working together:

class User
  include Mongoid::Document

  embeds_many :phones, :as => :identifiable
  embeds_many :emails, :as => :identifiable
  embeds_many :social_profiles, :as => :identifiable

  field :first_name, type: String
  field :middle_name, type: String
  field :last_name, type: String
  field :email, type: String
  field :password, type: String
end

class Identifier
  include Mongoid::Document
  embedded_in :identifiable, polymorphic: true  
  field :name, type: String # work, home, linked_in etc
  field :valid, type: Boolean
  field :validated_at, type: DateTime
end

class Email < Identifier
  field :email, type: String
end

class Phone < Identifier
  field :phone, type: String
end

class SocialProfile < Identifier
  field :url, type: String
end

  1. kandadaboggu-blog posted this
Blog comments powered by Disqus