Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 580
Adam Avatar asked Jan 09 '23 14:01

Adam


1 Answers

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.

like image 98
Ryan McGeary Avatar answered Jan 27 '23 18:01

Ryan McGeary