STI and Multiple Databases in Rails

I admit, I believed it when DHH said that Rails apps should communicate via REST if they want access to a shared database. I bought into the hype and even wrote a plugin to make this easier.

Well, it’s slow. I don’t have real numbers, of course, because I’m not the type of person to write down numbers frequently. However, it’s the difference between being able to sort users by a field in a different database or not.

So, I tried some stuff, and I discovered that to use a different database for some models, especially those with STI, it’s best to mix Sharing External ActiveRecord Connections with Null Instead of Empty String. I also discovered that for all descendants of the external connection class you must set_table_name.

To put code here, this is ncre_base.rb, from which MyNCRE-connecting models in LandBrokr derive:

class NcreBase < ActiveRecord::Base
  def self.descends_from_active_record?
    superclass == NcreBase
  end

  def self.class_name_of_active_record_descendant(klass)
    if klass.superclass == NcreBase then
      return klass.name
    elsif klass.superclass.nil? then
      raise ActiveRecordError, "#{name} doesn't descend from ActiveRecord::Base"
    else
      class_name_of_active_record_descendant klass.superclass
    end
  end
end

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*