method

table_name

Importance_3
v3.1.0 - Show latest stable - 1 note - Class: ActiveRecord::Base
table_name() public

Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.

Nested classes are given table names prefixed by the singular form of the parent’s table name. Enclosing modules are not considered.

Examples

class Invoice < ActiveRecord::Base
end

file                  class               table_name
invoice.rb            Invoice             invoices

class Invoice < ActiveRecord::Base
  class Lineitem < ActiveRecord::Base
  end
end

file                  class               table_name
invoice.rb            Invoice::Lineitem   invoice_lineitems

module Invoice
  class Lineitem < ActiveRecord::Base
  end
end

file                  class               table_name
invoice/lineitem.rb   Invoice::Lineitem   lineitems

Additionally, the class-level table_name_prefix is prepended and the table_name_suffix is appended. So if you have “myapp_” as a prefix, the table name guess for an Invoice class becomes “myapp_invoices”. Invoice::Lineitem becomes “myapp_invoice_lineitems”.

You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a “mice” table. Example:

class Mouse < ActiveRecord::Base
  set_table_name "mice"
end
Show source
Register or log in to add new notes.
August 16, 2008
1 thank

Examples of Setting the Prefix and Suffix

Both of the following will work for setting the prefix or suffix:

class Mouse < ActiveRecord::Base
  self.table_name_prefix = 'forum_'
end

and

class Mouse < ActiveRecord::Base
  def self.table_name_prefix
    'forum_'
  end
end