ruby-on-railsmodelroutessti

Rails STI override model_name in parent class for all subclasses


I am using STI in a Rails app and in order to not have to define routes for all subclasses, I put the following in each subclass:

def self.model_name
  Mapping.model_name
end

In the above example, Mapping is the parent model name. Example:

class UserMapping < Mapping; end

Having to put this in each subclass is not very DRY, so I'm looking for a way to set that in the parent somehow, so that each class that inherits from the parent automatically has the model name set as the parent model name.

Perhaps there is even a better way to overcome the routing issue that arises from STI unrelated to setting the model_name - I'm open to suggestions!

Thanks in advance!


Solution

  • Put this in your Mapping class:

    class Mapping < ActiveRecord::Base
      def self.inherited(subclass)
        super
        def subclass.model_name
          superclass.model_name
        end
      end
    end
    

    Afterwards, all child classes of Mapping will also inherit the parent's model_name.