Ruby on Rails/ActiveRecord/Naming

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Built-In Rails Tools/Command-Line Reference Index Next: ActiveRecord/Migrations

Naming[edit]

Basics[edit]

ActiveRecord uses convention for naming classes, tables and fields. Rails uses convention over configuration. ActiveRecord expects applications to follow certain naming conventions. These conventions extend from file naming, class naming, table naming and more. By default classes are singular, tables are plural, primary keys are id and foreign keys are table_id.

Note: There are also certain names that are reserved and should not be used in your model for attributes outside of the conventions defined in Rails:

  • lock_version
  • type - This is only used when you have single table inheritance and must contain a class name
  • id - Reserved for primary keys
  • table_name_count - Reserved for counter cache
  • position - Reserved for acts_as_list
  • parent_id - Reserved for acts_as_tree
  • lft - Reserved for acts_as_nested_set
  • rgt - Reserved for acts_as_nested_set
  • quote - Method in ActiveRecord::Base which is used to quote SQL
  • template

Classes[edit]

ActiveRecord classes are named in singular form.

Tables[edit]

Tables for ActiveRecord objects are named in plural form by default. This pluralization is often an initial point of contention for new Rails users.

For a class named 'Dog', the default table name is 'Dogs'.

If you need to change the table name there are several ways to override the default behavior.

Set use_pluralization[edit]

In config/environment.rb you can specify ActiveRecord::Base.use_pluralization = false. This will apply to all ActiveRecord objects.

Use set_table_name[edit]

You can call set_table_name to specify a custom table name for a particular model.

For example:

  class Dog < ActiveRecord::Base
    set_table_name 'dog'
  end

Override table_name[edit]

You can also override the table_name method and return a value.

For example:

  class Dog < ActiveRecord::Base
    def table_name
      'dog'
    end
  end