Ruby on Rails
Comprehensive Ruby on Rails framework reference for building web applications with MVC architecture
8 min read
railsrubymvcactive-recordbackendweb-frameworkgeneratorsmigrations
Table of Contents
Getting Started
New Rails Application
Create a new Rails application with various options
bash
✅ Default database is SQLite, use --database for PostgreSQL/MySQL
💡 --api flag creates lightweight API-only app
🔍 --skip-test useful if using RSpec instead of Minitest
⚡ Use rails new --help to see all available options
setupclinew-app
Rails Server & Console
Start development server and interactive console
bash
✅ Default server runs on localhost:3000
💡 Use rails c --sandbox to test without affecting database
🔍 reload! in console reloads code without restarting
⚡ rails server accepts same flags as rails s
serverconsoledevelopment
Generators
Model Generator
Generate models with migrations and attributes
bash
✅ Automatically creates migration, model, and test files
💡 Use references for associations (creates foreign key)
🔍 :index adds database index, :uniq adds unique index
⚡ rails destroy model reverses the generator
generatormodelmigration
Controller Generator
Generate controllers with actions and views
bash
✅ Creates controller, views, helper, and routes
💡 --skip-template-engine for API-only controllers
🔍 Namespaced controllers use slashes: api/v1/Users
⚡ Actions listed after controller name become methods
generatorcontrollercrud
Scaffold Generator
Generate complete CRUD resource with all components
bash
✅ Creates model, migration, controller, views, routes, tests
💡 Great for prototyping, customize afterwards
🔍 --api flag creates API-only scaffold without views
⚠️ Generates a lot of files - review before committing
generatorscaffoldcrudfull-stack
Migration Generator
Generate standalone database migrations
bash
✅ Rails infers migration content from name convention
💡 AddXxxToYyy and RemoveXxxFromYyy auto-generate code
🔍 Use CreateJoinTable for many-to-many relationships
⚡ Always review generated migration before running
generatormigrationdatabase
Database & Migrations
Database Commands
Create, migrate, and manage database
bash
✅ db:create creates database defined in database.yml
💡 db:reset drops and recreates from schema.rb
🔍 db:setup is for first-time setup, db:reset for refresh
⚡ Always backup production before db:reset or db:drop
databasemigrationssetup
Migration Methods
Common methods used in migration files
ruby
✅ t.timestamps adds created_at and updated_at
💡 Use references for foreign keys with index
🔍 precision and scale control decimal places
⚡ Add indexes for frequently queried columns
migrationsschemadatabase
Routes
Resourceful Routes
RESTful routes with resources
ruby
✅ resources generates 7 RESTful routes automatically
💡 Use only/except to limit generated routes
🔍 Shallow nesting prevents deep URL structures
⚡ Check routes with rails routes command
routesrestresources
Custom Routes
Define custom routes and root
ruby
✅ root route defines homepage (must be first)
💡 Use as: option to create custom path helper
🔍 Constraints validate route parameters
⚡ rails routes | grep posts to filter routes
routescustomhttp
Controllers
Controller Actions
Common controller patterns and responses
ruby
✅ Use before_action for common setup code
💡 Strong parameters required for mass assignment
🔍 respond_to handles multiple formats
⚡ Use includes() to avoid N+1 queries
controllersactionscrud
Filters & Callbacks
Before/after/around filters for controller actions
ruby
✅ before_action runs before controller actions
💡 Use only/except to limit filter scope
🔍 skip_before_action skips inherited filters
⚡ around_action wraps action execution
controllersfilterscallbacks
Models & Active Record
Model Associations
Define relationships between models
ruby
✅ belongs_to creates foreign key relationship
💡 dependent: :destroy deletes associated records
🔍 has_many :through for many-to-many relationships
⚡ Use counter_cache to avoid COUNT queries
modelsassociationsrelationships
Validations
Validate model data before saving
ruby
✅ Validations run before save/create/update
💡 Use presence: true for required fields
🔍 Custom validations via validate method
⚡ Conditional validations with if/unless
modelsvalidationsdata-integrity
Queries & Scopes
Query database with Active Record
ruby
✅ Use find_by instead of where().first
💡 includes() prevents N+1 query problems
🔍 Scopes make queries reusable and chainable
⚡ Use select() to fetch only needed columns
modelsqueriesactive-recordscopes
Callbacks
Lifecycle hooks for model operations
ruby
✅ Callbacks run automatically during object lifecycle
💡 before_validation runs before validations
🔍 Use conditional callbacks with if/unless
⚠️ Avoid complex logic in callbacks, use service objects
modelscallbackslifecycle