Skip to content

Instantly share code, notes, and snippets.

@pel-daniel
Last active September 11, 2017 20:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pel-daniel/53be9930c5284c5bd0a79f993ab216d8 to your computer and use it in GitHub Desktop.
Save pel-daniel/53be9930c5284c5bd0a79f993ab216d8 to your computer and use it in GitHub Desktop.
Rails conventions

Rails conventions

General

All filenames are in snake_case following the same conventions

  • Model: singular (e.g. Restaurant)
  • Controller: plural (e.g. RestaurantsController)
  • Table in DB: plural (e.g. restaurants)
  • URL's: all in plural (e.g. /restaurants, /restaurants/:id, /restaurants/new)

rails generate Commands

  • Create model: singular (because the name of the model is singular). e.g. rails g model Restaurant name:string rating:integer
  • Create migration: plural (because we use the name of the table). e.g. rails g migration AddDescriptionToRestaurants description:text
  • Create controller: plural e.g. rails g controller Restaurants index show

Model (singular)

ActiveRecord methods

All in singular, because all ActiveRecord's methods are linked to the model. Examples:

  • Restaurant.all
  • Restaurant.create(name: "Burger King", rating: 2)
  • Restaurant.find(params[:id])

Associations

  • Singular in the belongs_to. Because it belongs to one element.
  • Plural in the has_many. Because it has many elements.

e.g.

class Restaurant < ActiveRecord::Base
  has_many :reviews
end

class Review < ActiveRecord::Base
  belongs_to :restaurant
end

Routes

Resources

Plural when defining a route for a resource:

  resources :restaurants

Route helpers

  • index: plural (because we are showing a list of elements). e.g. restaurants_path. Can also be used used for create.
  • show: singular (we are showing just one element, it needs the element inside parenthesis). e.g. restaurant_path(@restaurant). Can also be used for update & delete.
  • new: singular. e.g. new_restaurant_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment