How to solve rails 4 UndefinedTable Error when creating namespaced models

In a given rails 4 application, I have two namespaced models with a has_many association between them:

# models/review/asset_type.rb
module Review
  class AssetType < ActiveRecord::Base
    belongs_to :review_asset_category, class_name: Review::AssetCategory
  end
end

# models/review/asset_category.rb
module Review
  class AssetCategory < ActiveRecord::Base
    has_many :review_asset_types, class_name: Review::AssetType,
             foreign_key: 'review_asset_category_id'
  end
end

With migrations as:

class CreateReviewAssetCategories < ActiveRecord::Migration
  def change
    create_table :review_asset_categories do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

The migrations ran well but everytime I ran the tests I received the error:

Failure/Error: it { is_expected.to respond_to(:name) }
     ActiveRecord::StatementInvalid:
       PG::UndefinedTable: ERROR:  relation "asset_categories" does not exist
       LINE 5:                WHERE a.attrelid = '"asset_categories"'::regc...
                                                 ^
       :               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                            pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                       FROM pg_attribute a LEFT JOIN pg_attrdef d
                         ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                      WHERE a.attrelid = '"asset_categories"'::regclass
                        AND a.attnum > 0 AND NOT a.attisdropped
                      ORDER BY a.attnum

The solution is simple, just add this class method to each model or to the module that is namespacing the models:

module Review
  def self.table_name_prefix
    'review_'
  end
end

I hope this simple advice will save some time for other developers 🙂

Leave a Comment