Search code examples
ruby-on-railstypessingle-table-inheritancesti

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


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.


Solution

  • 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