tables and models within modules in Rails

about models within modules and corresponding table names in Rails.

when searching for table AR always uses model name without modules. e.g. for Stats::Google::Analytics::McfStat it will search for mcf_stats table.

NOTE: AR still finds table sites_descriptions for Site::Description model - when module (Site) is a class of existing model (Site::Description).

to use module name as table name prefix it’s necessary to define table name prefix for this module:

e.g. for Stats::Google::Analytics::McfStat create app/models/stats/stats.rb:

module Stats
  module Google
    module Analytics
      def self.table_name_prefix
        'google_analytics_'
      end
    end
  end
end

as shown above table name prefix doesn’t have to match module hierarchy.

NOTE: don’t use :: notation when defining table name prefixes!

different table name prefixes for different nested modules

table name prefix for high level module will override one for any nested module if defined before the latter:

app/models/stats/stats.rb:

module Stats
  def self.table_name_prefix
    'stats_'
  end
end

module Stats
  module Google
    module Analytics
      def self.table_name_prefix
        'google_analytics_'
      end
    end
  end
end

to have different table name prefixes for different nested modules: