This principle helps you write less setup code by following common rules. Rails knows what to do if you follow its naming and structure.
Convention over configuration principle in Ruby on Rails
No special code syntax; it means following Rails naming and folder rules.For example, a model named Article uses a database table named articles automatically.
Controllers named ArticlesController handle views in app/views/articles/ folder by default.
articles automatically.# Model file: app/models/article.rb class Article < ApplicationRecord end
app/views/articles/index.html.erb by default.# Controller file: app/controllers/articles_controller.rb class ArticlesController < ApplicationController def index @articles = Article.all end end
articles matching the model Article.# Migration file: db/migrate/20240101000000_create_articles.rb class CreateArticles < ActiveRecord::Migration[7.0] def change create_table :articles do |t| t.string :title t.text :content t.timestamps end end end
This example shows a Post model, a controller PostsController, and a view in app/views/posts/index.html.erb. Rails connects them automatically because of the naming conventions.
# app/models/post.rb class Post < ApplicationRecord end # app/controllers/posts_controller.rb class PostsController < ApplicationController def index @posts = Post.all end end # app/views/posts/index.html.erb <% @posts.each do |post| %> <h2><%= post.title %></h2> <p><%= post.content %></p> <% end %>
Following Rails conventions saves time and reduces errors.
You can override conventions, but it requires extra configuration.
Always name files, classes, and folders carefully to match Rails expectations.
Rails uses conventions to guess what you want, so you write less setup code.
Models, controllers, views, and database tables follow naming rules to connect automatically.
Following these rules helps you build apps faster and with fewer mistakes.