Rails STI: How to change mapping between class name & value of the 'type' column

arun picture arun · Apr 25, 2014 · Viewed 10.8k times · Source

Because of company rules I can't use our domain class names; I am going to use an analogy instead. I have a table called projects which has a column called 'type' with possible values as 'indoor' & 'outdoor'. Records having indoor and outdoor have clear functionality separation and would fit pretty neatly as a STI implementation. Unfortunately I can't change the type-names and can't add classes inside the global namespace. Is there a way to specify a different value for 'type'?

Note: I am not trying to use a different column name instead of 'type' for STI. I am looking to have a different value for type, other than my class name.

Answer

VAIRIX picture VAIRIX · Apr 25, 2014

You can try something like this:

class Proyect < ActiveRecord::Base
end

Then the Indoor class but with Other name

class Other < Proyect
  class << self
    def find_sti_class(type_name)
      type_name = self.name
      super
    end

    def sti_name
      "Indoor"
    end
  end
end

The same apply for Outdoor class. You can check sti_name in http://apidock.com/rails/ActiveRecord/Base/find_sti_class/class