ActiveRecord: table_name overrides
This course explains how ActiveRecord maps a model class to its database table and how self.table_name overrides that mapping. It starts with the Rails naming convention and the table_name_prefix method defined by this app's namespace modules. It then shows why the app keeps table names separate from Ruby namespaces. Three kinds of override follow: one that strips a prefix, one that changes nothing, and one that adds precision. The final lessons cover what table_name leaves untouched, such as foreign keys and migrations.
What you'll learn
- ✓How Rails derives a table name by demodulizing, underscoring and pluralizing the class name
- ✓How a module's table_name_prefix sets the default table name for its models
- ✓Why table names are kept separate from Ruby namespaces
- ✓Three jobs of self.table_name: stripping a prefix, restating the convention and adding precision
- ✓Why foreign keys and migrations do not depend on a model's table_name
- ✓How a wrong table_name fails with PG::UndefinedTable
Rails' naming convention, and where this app breaks it
Every model these courses have touched, like Catalog::Course, Enrollment::Enrollment and Identity::User, finds its table without anyone writing mapping code, most of the time. Rails' rule is to take the class name, demodulize it (drop any Module:: prefix), underscore it and pluralize it. Article…
Read the full lesson free →Curriculum
7 lessonsRails' naming convention, and where this app breaks it
How Rails turns a class name into a table name, and why Catalog::Course needs self.table_name.
table_name_prefix: the namespace's default
The table_name_prefix method on namespace modules, and how Community::Comment resolves to community_comments through it.
Separating table names from domain structure on purpose
Why this app keeps table names apart from namespaces, so moving a class never forces a table rename.
When the override changes nothing at all
Identity has no prefix, so User needs no override and the override in UserPreference changes nothing.
When the override changes something on purpose
Identity::Authentication overrides its table to identity_authentications, adding precision the plain convention would never supply.
What table_name does not affect
Foreign keys come from association names, a wrong table_name raises PG::UndefinedTable, and migrations never read models.
Putting it together: three overrides, one mechanism
A side-by-side look at three overrides using one mechanism, and how to tell which job each does.