Ror Naming
Ror Naming
Introduction.
In Rails it is so important to get the naming conventions correct. This is all part of
the DRY ( Don't Repeat Yourself ) paradigm of Rails. This is particularly important
at the beginning of a new project. Grasping this logic will go a long way to gaining
a full understanding of Rails . If you get it wrong, progress can be frustrating.
This document describes the naming conventions Ruby on Rails uses in regard to the
models, controllers, source files, classes, table names, relationships, methods, routing
& the corresponding folder structures. These are created via the 'ruby script/'
command line generator.
I will use a simple Contact / Category two table structure in a 'play' project.
On page three there are images showing the folder structure in the app folder and the
table names in SQLite Manager.
Project Creation:
The name of a new Rails project is entirely up to you. But keep it simple, best not to
have any special characters. ( e.g. 'rails play' ).
Models.
A model created via the command line generator, refers to the model as singular. So
in our example of categories and contacts we use....
When the migration files for these models are created with 'rake db:migrate', the
tables created will be plural ( i.e. categories and contacts ).
The model files that are created are singular within the apps/models folder
e.g. category.rb ( see image below )
page 1 of 3
Controllers.
When a controller is created via 'ruby script/generate' the plural name is used ( unlike
models ).
i.e.
$ ruby script/generate controller Contacts index
The corresponding view files are created within a folder (auto-created if it does not
already exist) that is plural.
( e.g. app/views/contacts/index.html.erb )
Scaffold - If scaffold is used as the generator (which creates the model and controller
in one action!) the information described above is identical.
Routing.
When the Scaffold generator is used it also creates entries in your routes.rb file
( located in the config folder )
Restful entries generated are of a plural nature and look like this:
map.resources :contacts
map.resources :categories
Relationships.
In the model files the relationship code uses singular references for belongs to.
e.g.
class Contact < ActiveRecord::Base
belongs_to :category
end
page 2 of 3
Controller Methods.
In controllers, find methods use the singular name of the model.
e.g.
def index
@categories = Category.find(:all)
Note that the instance variable @categories can be any name, but using the plural
name here is logical as the index method is finding all the categories.
e.g. 2
def show
@category = Category.find(params[:id])
Note that the instance variable @category can be any name, but using the singular
name here is logical as the show method is finding a single category.
Figure – 2
Shows the plural table names
created in our 'play' project.
Figure – 1
Shows the names of files and folders
within our 'play' project app folder.
page 3 of 3