Search code examples
ruby-on-railsrubyactiverecordforeign-keyssti

Redefine foreign key name for all associations in Rails


I have an STI model with many associations:

class MyModel < ActiveRecord::base
  has_many :things
  has_many :other_things
  # ... a lot of `has_many`
end

Then I add non STI model as nested just to add some specific behaviour to MyModel without extending it directly:

class Nested < MyModel
  self.inheritance_column = nil
end

But then my associations don't work. They have my_model_id column because they refer to MyModel and they should refer to Nested as well. But all these has_many's expect to use nested_id column as a foreign key (it depends on class name).

I could've typed inside class Nested:

has_many :things, foreign_key: 'my_model_id'
has_many :other_things, foreign_key: 'my_model_id'

But if it's possible, how to specify the foreign key for all the associations at once in Nested class?


Solution

  • My solution might be is not recommended, but it works. Here it is:

    class Nested < MyModel
      def self.name
        MyModel.name
      end
    end
    

    ActiveRecord will be looking for my_model_id foreign key for all the associations defined or redefined in Nested and MyModel classes.