Oct 28

Ruby and Rails Naming Conventions

etienne @ 10:15 am

I’ve been looking for a consolidated list of all Ruby and Rails naming conventions without too much luck so I’ve started my own. I find I always forget the naming convention especially as I move between projects that use different languages.

Please let me know of any others that I have missed. 

Naming Conventions

Ruby Naming Convention

Ruby uses the first character of the name to help it determine it’s intended use.

Local Variables
Lowercase letter followed by other characters, naming convention states that it is better to use underscores rather than camelBack for multiple word names, e.g. mileage, variable_xyz

Instance Variables
Instance variables are defined using the single "at" sign (@) followed by a name. It is suggested that a lowercase letter should be used after the @, e.g. @colour 

Instance Methods
Method names should start with a lowercase letter, and may be followed by digits, underscores, and letters, e.g. paint, close_the_door

Class Variables
Class variable names start with a double "at" sign (@@) and may be followed by digits, underscores, and letters, e.g. @@colour

Constant
Constant names start with an uppercase letter followed by other characters. Constant objects are by convention named using all uppercase letters and underscores between words, e.g. THIS_IS_A_CONSTANT

Class and Module
Class and module names starts with an uppercase letter, by convention they are named using MixedCase, e.g. module Encryption, class MixedCase

Global Variables
Starts with a dollar ($) sign followed by other characters, e.g. $global

Rails Naming Convention

Rails use the same naming convention as Ruby with some additions:

Variable
Variables are named where all letters are lowercase and words are separated by underscores, e.g. order_amount, total

Class and Module
Classes and modules use MixedCase and have no underscores, each word starts with a uppercase letter, e.g. InvoiceItem

Database Table
Table names have all lowercase letters and underscores between words, also all table names need to be plural, e.g. invoice_items, orders

Model 
The model is named using the class naming convention of unbroken MixedCase and is always the singular of the table name, e.g. table name might be orders, the model name would be Order. Rails will then look for the class definition in a file called order.rb in the /app/models directory. If the model class name has multiple capitalised words, the table name is assumed to have underscores between these words.

Controller
Controller class names are pluralized, such that OrdersController would be the controller class for the orders table.  Rails will then look for the class definition in a file called orders_controller.rb in the /app/controllers directory.

Files, Directories and other pluralization
Files are named using lowercase and underscores. Assuming we have an Orders controller then the following other conventions will apply:

  • That there is a helper module named OrdersHelper in the orders_helper.rb found in the app/helpers directory
  • Rails will look for view template files for the controller in the app/views/orders directory
  • Output from this view will then be used in the layout defined in the orders.html.erb in the app/views/layouts directory
  • Test files including order_test.rb will be created in the /test/unit directory, a file will be created in the /test/fixtures directory called orders.yml and finally a file called orders_controller_test.rb will be created in the /test/functional directory

Primary Key
The primary key of a table is assumed to be named id.

Foreign Key
The foreign key is named with the singular version of the target table name with _id appended to it, e.g. order_id in the items table where we have items linked to the orders table.

Many to Many Link Tables
Tables used to join two tables in a many to many relationship is named using the table names they link, with the table names in alphabetical order, for example items_orders.

Automated Record Timestamps
You can get ActiveRecord to automatically update the create and update times of records in a database table. To do this create two specially named columns created_at and updated_at to your table, i.e. t.datetime :created_at and t.datetime :updated_at. If you only want to store the date rather than a date and time, use :created_on and :updated_on.

Naming Convention Summary 

Model Naming Convention

Table: orders
Class: Order
File: /app/models/order.rb
Primary Key: id
Foreign Key: customer_id
Link Tables: items_orders

Controller Naming Convention

Class: OrdersController
File: /app/controllers/orders_controller.rb
Layout: /app/layouts/orders.html.erb

View Naming Convention

Helper: /app/helpers/orders_helper.rb
Helper Module: OrdersHelper
Views: /app/views/orders/… (list.html.erb for example)

Tests Naming Convention

Unit: /test/unit/order_test.rb
Functional: /test/functional/orders_controller_test.rb
Fixtures: /test/fixtures/orders.yml

  

32 Responses to “Ruby and Rails Naming Conventions”

  1. Salam Fall says:

    Thanx a million I am a newbie to RoR, and some tutorials dont really make it clear that you have to stick to the naming concentions to get on the Wagon.

    Thanks Again!

  2. Abdou Salam Madior Fall says:

    Thanks a million I am a newbie to RoR, and some tutorials dont really make it clear that you have to stick to the naming conventions to get on the Wagon.

    Thanks Again!

  3. etienne says:

    No problem at all, I had the same issue. I could not find a list of conventions anywhere telling me what I needed to do, very frustrating. If you come across any other conventions please let me and I’ll add it to the list.

  4. Ruby and Rails Naming Conventions Article Missing from Search Engines | IT.Signals says:

    […] Ruby and Rails Naming Conventions […]

  5. Naming Conventions - Ruby and Ruby on Rails | IT.Signals says:

    […] Ruby and Rails Naming Conventions […]

  6. Introducing Railscheck - A Q/A verification tool for Ruby On Rails « 41 technologies says:

    […] in the case of Ruby On Rails, which is of heavily opinionated nature, there are many conventions that can be broken by mistake which may introduce errors that do no show up initially. This […]

  7. Alan Smith says:

    One more that doesn’t affect many things, but still:
    ? after a method call means it returns a boolean and has NO side effects
    ! after a method call means it modifies the object it is called on OR the parameters passed in. This seems to be inconsistent at best.

  8. Ruby on Rails for a .NET Developer - Part 1 | Emad Ibrahim says:

    […] There is more information about Rails and Ruby naming conventions over here. […]

  9. Jeffrey Lee says:

    I haven’t been able to find an answer on a particular convention for PKs/FKs. I have an identifiers table with various fields, a users table and lets say a profiles table. The users table has a primary key of identifier_id (i.e., the PK is a FK). This works perfectly fine; however, I do not know how to extend this further down. In the profiles table I need to reference the users table, but do I use user_id or something different? I have not found documentation for this and haven’t started developing this app yet (I want to get the DB set first).

  10. etienne says:

    Hi Jeffrey,

    If I understand you correctly you could setup your structure like this:

    identifiers
    id
    |
    |
    users
    id
    identifier_id
    |
    |
    profiles
    id
    user_id

    You are able to access the user of the profile by using the user_id, you can then find the identifier by using the identifier_id in the users table.

  11. Matthew says:

    Thank you very much for the concise summary.

  12. raziel says:

    Okay, this is more of a practical question, but I want to create a “blog” in rails. I however, do not want the controller to be called “Blogs”, and I don’t want the table to be called “blogs”.

    The best thing I can think of is to call it something like “articles”, however, this breaks other things, like the current_page? (or whatever) method.

    Any feedback is appreciated!

  13. Gunnar Djurberg says:

    What if I want to organize some models in a module? E.g. what should I call the table corresponding to Admin::Group ? “Admin::Group”.tableize => “admin/groups” which is not acceptable table name. Just using groups could cause name clash.

  14. Joseph says:

    Hi Etienne,

    Many thanks for the post.

    I have a question; I need to create a join table and the convention is to use the other two table names in alphabetic order to name this join table. One of my tables is called “words” and the other one is called “word_types2. My question is: what is the alphabetic order here? Does “s” in words come before “_” in word_types or is it the other way around? My guess is that the first is true and therefore the join table should be called: words_word_types.

    Many thanks!!

  15. Joseph says:

    Sorry, there is a typo in my previous comment; the second table name should read “word_types”, not “word_type2.
    Regards.

  16. etienne says:

    Hi Joseph,

    That is a good question, I like you am not sure about the answer in this instance but I think I’d agree words_word_types would be the way to go.

  17. Joseph says:

    Hi Etienne,

    Thanks, I’ll dig around a bit and will post the answer here when I find out.

    Cheers

  18. Joseph says:

    Got it!

    I found here: http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000430 that:

    The lexical order: “is calculated using the

  19. Joseph says:

    Sorry, part of the post got cut off. I’ll try again..

    The lexical order: “is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one.”

    What that basically means is that, contrary to what we thought, word_types comes before words, because it is longer, and therefore the join table should be named “word_types_words”.

    I am still not quite sure, though, whether the underscore (_) would come before or after alphabetic characters, but for now my query is answered.

  20. Andrew says:

    Just a note to say thank you for compiling this helpful list.

    All the best,
    Andrew

  21. etienne says:

    Hi Andrew,

    Thank you for the feedback, I’m glad you found it helpful.

    Cheers,

    Etienne.

  22. gsw says:

    Also, Class and Module names cannot contain “.”

  23. lagattack says:

    What about methods that end in an exclamation point? I think that there is a difference between Ruby and Rails conventions here. I believe that in Ruby, methods appended with ! modify the object they are working with instead of returning a new object, whereas in Rails, these methods will throw an exception if the operation fails.

    For example:

    Ruby, Array.collect vs Array.collect!
    Rails ActiveRecord::Base.save vs ActiveRecord::Base.save!

    Thanks,

    Janz

  24. Harry Wood says:

    “If the model class name has multiple capitalised words, the table name is assumed to have underscores between these words” …. as is the class definition filename

  25. N.I.K says:

    as i know, the tables should have “s”, and the models should not, but what if my table name consists of two words like “contribution_status” (note:::: it is not a relation or a link table) is it correct to be named “contributions_statuses” as a table, and “Contribution_status” as a model ?

  26. hans says:

    Very helpful!
    Routing is yet another reason for sticking to rails nanming conventions:
    Rails dynamically creates very useful helper methods according to your controller name.
    You can see the created routes when you perform ‘rake routes’ where the helper methods
    base strings are listed left hand.

  27. Things I Wish I’d Know About Ruby & Rails | Bulletproof Technology says:

    […] brief overview of Ruby and Rails naming conventions are here. More information about Rails inflection rules are in this blog […]

  28. Delicious Bookmarks for August 21st from 13:08 to 21:42 « Lâmôlabs says:

    […] Ruby and Rails Naming Conventions | IT.Signals – August 21st ( tags: rails ruby conventions naming rubyonrails programming reference standards ) […]

  29. Michael Mahemoff (@mahemoff) says:

    How about adding HTML/JS/CSS conventions to this list, particularly element IDs and class names. (Which seems to be “foo-bar”.)

  30. Sagar_Junnarkar says:

    Thank you so much for updating on ROR naming conventions.
    I have just started my 1st project.
    There are lots of conventions in rails.
    I hope that will make my task easy.

  31. Programming languages - Ruby | Pearltrees says:

    […] Ruby and Rails Naming Conventions | IT.Signals I’ve been looking for a consolidated list of all Ruby and Rails naming conventions without too much luck so I’ve started my own. I find I always forget the naming convention especially as I move between projects that use different languages. Please let me know of any others that I have missed. Naming Conventions Ruby Naming Convention Ruby uses the first character of the name to help it determine it’s intended use. […]

  32. Nogarudo says:

    The partial layout names starts with an underscore “_”. For example: _new.html

Leave a Reply