Naming Conventions
Get familiar with some of the conventions of writing controller and view names in Ruby.
We'll cover the following
Newcomers to Rails are sometimes puzzled by the way it automatically handles naming. They’re surprised that they call a model class Person
and Rails somehow knows to go looking for a database table called people
. In this lesson, we’ll learn how this implicit naming works.
The rules here are the default conventions used by Rails. We can override all of these conventions using configuration options.
Mixed case, underscores, and plurals
We often name variables and classes with short phrases. In Ruby, the convention is to have variable names where the letters are all lowercase and words are separated by underscores. Classes and modules are named differently, in that there are no underscores and each word in the phrase, including the first, is capitalized. This is called “mixed case,” for fairly obvious reasons. These conventions lead to variable names such as order_status
and class names such as LineItem
.
Rails take this convention and extend it in two ways. First, it assumes that database table names, such as variable names, have lowercase letters and underscores between the words. Rails also assume that table names are always plural. This leads to table names such as orders
and third_parties
.
On another axis, Rails assumes that files are named using lowercase with underscores.
Rails use this knowledge of naming conventions to convert names automatically. For example, our application might contain a model class that handles line items. We’d define the class using the Ruby naming convention and call it LineItem
. From this name, Rails will automatically deduce the following:
-
That the corresponding database table will be called
line_items
. That’s the class name, converted to lowercase, with underscores between the words, and pluralized. -
Rails also knows to look for the class definition in a file called
line_item.rb
, which is in theapp/models
directory.
Rails controllers have additional naming conventions. If our application has a store controller, then the following happens:
-
Rails assumes the class is called
StoreController
and that it’s in a file namedstore_controller.rb
in theapp/controllers
directory. -
Rails also looks for a helper module named
StoreHelper
in the filestore_helper.rb
located in theapp/helpers
directory. -
It will look for view templates for this controller in the
app/views/store directory
. -
It will by default take the output of these views and wrap them in the layout template contained in the file
store.html.erb
orstore.xml.erb
in the directoryapp/views/layouts
.
All these conventions are shown in the following tables.
Get hands-on with 1400+ tech skills courses.