Last Updated: September 09, 2019
·
31.03K
· drywheattoast

Easily namespace your Rails models

If you implement the class method tablenameprefix inside a regular module:

module Invoice
  def self.table_name_prefix
    'invoice_'
  end
end

Then any models you nest inside that module will prepend that prefix onto their table name:

module Invoice
  class Customer < ActiveRecord::Base
  end
end

Invoice::Customer.table_name # => "invoice_customers"

This is an easy and straightforward way to namespaces models in both your database and application.

1 Response
Add your response

I was wondering how to generate the "namespaced" (at least prefixed) tables though through a Rails migration. This site had this suggestion, which works:

$ rails g model admin/user
over 1 year ago ·