Read more

Rails: namespacing models with table_name_prefix instead of table_name

Daniel Straßner
September 07, 2017Software engineer at makandra GmbH

When you want to group rails models of a logical context, namespaces are your friend. However, if you have a lot of classes in the same namespace it might be tedious to specify the table name for each class seperately:

class Accounting::Invoice < ApplicationRecord
  self.table_name = 'accounting_invoices'
  ...
end

class Accounting::Payment < ApplicationRecord
  self.table_name = 'accounting_payments'
  ...
end
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

A replacement for the self.table_name-assignment is the table_name_prefix in the module definition:

module Accounting
  def self.table_name_prefix
    'accounting_'
  end
end

class Accounting::Invoice < ApplicationRecord
  ...
end

class Accounting::Payment < ApplicationRecord
  ...
end

Rails will be able to derive the table name accounting_invoices for Accounting::Invoice.

Posted by Daniel Straßner to makandra dev (2017-09-07 11:59)