Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...