Skip to main content
Back to Journal
Ruby-On-Rails

Tips: Rails DB Fun

Rails Database Tips

Working with databases in Ruby on Rails is made elegant by ActiveRecord, but there are tips and tricks that can save you time and headaches.

Migrations

Migrations are Ruby classes that allow you to create and modify database tables. They provide a version control system for your database schema:

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end

Useful Commands

# Create the database
rails db:create

# Run pending migrations
rails db:migrate

# Rollback the last migration
rails db:rollback

# Reset the database
rails db:reset

# Seed the database
rails db:seed

ActiveRecord Queries

# Find by ID
Post.find(1)

# Find by attribute
Post.find_by(title: "My Post")

# Where clause
Post.where(published: true)

# Order
Post.order(created_at: :desc)

# Limit
Post.limit(10)

Associations

ActiveRecord associations define relationships between models. The most common are belongs_to, has_many, has_one, and has_many :through.

RubyRailsDatabaseActiveRecord