Persist relation to a class (and not a class instance) in Ruby on Rails with Mongoid Assume my users can subscribe to several plan_types. I want to define those plans as classes, and be able to keep, for each user, a reference to a subscription_plan and also a presubscription_plan. This is like a State pattern :

class Payment::SubscriptionPlan
  def self.max_subscription_quantity
    120
  end 
end

class Payment::ConcretePlan1 &lt; Payment::SubscriptionPlan
  def self.commitment_period
    2.months
  end
end

class Payment::ConcretePlan2 &lt; Payment::SubscriptionPlan
  def self.max_subscription_quantity
    50
  end
end


What is the best way to "persist" the relation to a class in the database ? Currently I was doing the following using the as_enum gem

class Settings
  setting :subscription_plans, type: Array, default: [
    Payment::ConcretePlan1, 
    Payment::ConcretePlan2
  ]
end

class User
  as_enum :subscription_plan, Settings.subscription_plans, map: :string
  as_enum :presubscription_plan, Settings.subscription_plans, map: :string

  def subscription_plan
    return nil if super.nil?
    Payment.const_get(super.to_s.demodulize)
  end

  def presubscription_plan
    return nil if super.nil?
    Payment.const_get(super.to_s.demodulize)
  end
end


The current implementation works but I'm not sure this is the best way to tackle the problem
It works that's for sure. 

But enums could just as easily be defined in the database. Now that you've already got it working with enums, I would say stick with enums untill you have a good reason to change it.

anyways, here's how i probably would have done it: 

e.g.


user has_many subscription_plans
subscription_plan can belong to many users.
Limit the ability for a user to have a max of two, one of each type. Or the user must have two at any one time etc.




You get the picture. You can change the subscription plan table to suit your needs.

Hope this helps.