There are many Rails conventions that we need to follow. It's absolutely normal for beginners to feel confused. Our job is to help you navigate with ease.
Rails follows the idea of convention over configurations. What does this mean? Rails focuses on following convention (standards) first and allowing configurations (customizations) second.
Convention is following a common standard and pattern. Every Rails project will have a folder structure that's extremely similar (almost identical). The best practices are built-in. You can jump between different Rails projects easily because you know exactly where files are located, and how things are generally done.
On the other hand, many other web development frameworks do not follow this principle. This means that they do not have conventions. Every project looks different, as the file locations and structures are all different. So, it's hard for you to jump between different projects. These frameworks only offer configurations.
We will also explain why it's beneficial for us to learn these conventions even when it's painful.
First of all, you might be confused with when to use singular words vs plural words. Like what's the difference between :user and :users? Is it referring to the User model? Is it referring to the User database table? Is it referring to the Users controller?
When should it be :users vs User? When should it be Capitalized or use :symbol?
When should it be :first_name vs FirstName? When should we add under_score?
Let us go through different conventions step-by-step.
In a database migration file,
language=>ruby
class AddEmailToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :email
end
end
- The class name AddEmailToUsers follows the format of Add[capitalized column name]To[capitalized table name in plural]. In this case, we are adding the email column to Users table. Other examples can be AddIdToSessions, AddContentToComments, AddFirstNameToUsers.
- The add_column method add_column :users, :email follows the format of add_column :[table name in plural], :[column name]. Other examples can be add_column :sessions, :id, add_column :comments, :content, add_column :users, :first_name.
- Note, because the column name first name is two words, we use underscore to represent it in a single word first_name.
In a model file,
language=>ruby
class User < ApplicationRecord
belongs_to :group
has_many :comments
end
- The class name User follows the format of [capitalized table name in singular]. In this case, it's User. Other examples can be Session, Comment, Question.
- A user belongs to a group because a group has many users, so belongs_to :group follows the format of belongs_to :[table name in singular].
- Similarly, a user has many comments, so has_many :comments follows the format of has_many :[table name in plural].