Search code examples
modulepolymorphismlegacy

Polymorphic class moved to Legacy Module and is looking for polymorphic type Legacy::Class instead of Class


I moved the legacy code into a Legacy Module which uses a separate read-only database (the old MySQL database) as we have moved to PostgreSQL for the new version.

Everything queries fine until we get to the Polymorphic associations. It wants to look for eventable_type: 'Legacy::Schedule' instead of just 'Schedule'.

I could do an update on the field to change to 'Legacy::Schedule', but I don't think that is the cleanest solution. I would like to just modify the ActiveRecord query in the API or if there is a relations hack I would prefer that also.

Here is example of what I have:

class Legacy::LegacyData < ActiveRecord::Base
  self.abstract_class = true

  case Rails.env
  when "production"
    establish_connection :legacy_production
  when "development"
    establish_connection :legacy_development
  when "test"
    establish_connection :legacy_test
  else
    puts "connection: Rails.env error on establish_connection"
  end
end

,

module Legacy
  class Event < Legacy::LegacyData
    belongs_to :eventable, polymorphic: true
    ...
  end
end

,

module Legacy
  class Schedule < Legacy::LegacyData
    has_many :events, as: :eventable

    ...
  end
end

Solution

  • Inside Legacy::Event

    def eventable
      if self.eventable_type == 'Schedule'
        Legacy::Schedule.find(self.eventable_id)
      else
        Legacy::OtherClass.find(self.eventable_id)
      end
    end
    

    UPDATE:

    This is incomplete. Does not account for instance when Legacy::Schedule queries or builds on its events association where it then still queries for Legacy::Schedule