Software Architectย Guide:๐Ÿ’ก Understanding Design Patterns & Anti-Patterns in Ruby

In the world of software development, design patterns and anti-patterns play a critical role in writing maintainable, clean, and scalable code. As a Ruby developer, mastering these concepts will help you design robust applications and avoid common pitfalls.


What are Design Patterns?

Design patterns are time-tested, reusable solutions to common problems in software design. They aren’t code snippets but conceptual templates you can adapt based on your needs. Think of them as architectural blueprints.

๐Ÿงฑ Common Ruby Design Patterns

1. Singleton Pattern

the_logger = Logger.new
class Logger
  @@instance = Logger.new

  def self.instance
    @@instance
  end

  private_class_method :new
end

Use when only one instance of a class should exist (e.g., logger, configuration manager).

๐Ÿง  What is the Singleton Pattern?

The Singleton Pattern ensures that only one instance of a class exists during the lifetime of an application. This is useful for managing shared resources like:

  • a logger (so logs are not duplicated or misdirected),
  • a configuration manager (so all parts of the app read/write the same config),
  • or a database connection pool.

๐Ÿ” Why private_class_method :new?

This line prevents other parts of the code from calling Logger.new, like this:

Logger.new  # โŒ Will raise a NoMethodError

So, you’re restricting object creation from outside the class.

Q) Then how do you get an object of Logger?

By using a class method like Logger.instance that returns the only instance of the class.

โœ… Full Singleton Example in Ruby

class Logger
  # Create and store the single instance
  @@instance = Logger.new

  # Provide a public way to access that instance
  def self.instance
    @@instance
  end

  # Prevent external instantiation
  private_class_method :new

  # Example method
  def log(message)
    puts "[LOG] #{message}"
  end
end

# Usage
logger1 = Logger.instance
logger2 = Logger.instance

logger1.log("Singleton works!")

puts logger1.object_id == logger2.object_id  # true

๐Ÿงพ Explanation:

  • @@instance = Logger.new: Creates the only instance when the class is loaded.
  • Logger.instance: The only way to access that object.
  • private_class_method :new: Prevents creation of new objects using Logger.new.
  • logger1 == logger2: โœ… True, because they point to the same object.

๐Ÿ’ฌ Think of a Real-World Example

Imagine a central control tower at an airport:

  • There should only be one control tower instance managing flights.
  • If each plane connected to a new tower, it would be chaos!

The Singleton pattern in Ruby ensures there’s just one control tower (object) shared globally.


2. Observer Pattern

class Order
  include Observable

  def place_order
    changed
    notify_observers(self)
  end
end

class EmailNotifier
  def update(order)
    puts "Email sent for order #{order.id}"
  end
end

order = Order.new
order.add_observer(EmailNotifier.new)
order.place_order

Use when one change in an object should trigger actions in other objects.

๐Ÿ” Observer Pattern in Ruby โ€“ Explained in Detail

The Observer Pattern is a behavioral design pattern that lets one object (the subject) notify other objects (the observers) when its state changes.

Ruby has built-in support for this through the Observable module in the standard library (require 'observer').

How it Works

  1. The Subject (e.g., Order) includes the Observable module.
  2. The subject calls:
    • changed โ†’ marks the object as changed.
    • notify_observers(data) โ†’ notifies all subscribed observers.
  3. Observers (e.g., EmailNotifier) implement an update method.
  4. Observers are registered using add_observer(observer_object).

๐Ÿงช Complete Working Example

require 'observer'

class Order
  include Observable
  attr_reader :id

  def initialize(id)
    @id = id
  end

  def place_order
    puts "Placing order #{@id}..."
    changed                      # Mark this object as changed
    notify_observers(self)       # Notify all observers
  end
end

class EmailNotifier
  def update(order)
    puts "๐Ÿ“ง Email sent for Order ##{order.id}"
  end
end

class SMSNotifier
  def update(order)
    puts "๐Ÿ“ฑ SMS sent for Order ##{order.id}"
  end
end

# Create subject and observers
order = Order.new(101)
order.add_observer(EmailNotifier.new)
order.add_observer(SMSNotifier.new)

order.place_order

# Output:
# Placing order 101...
# ๐Ÿ“ง Email sent for Order #101
# ๐Ÿ“ฑ SMS sent for Order #101

๐Ÿง  When to Use the Observer Pattern

  • You have one object whose changes should automatically update other dependent objects.
  • Examples:
    • UI updates in response to data changes
    • Logging, email, or analytics triggers after a user action
    • Notification systems in event-driven apps

Updated Observer Pattern

require 'observer'

class Order
  include Observable
  attr_reader :id

  def initialize(id)
    @id = id
  end

  def place_order
    changed
    notify_observers(self)
  end
end

class EmailNotifier
  def update(order)
    puts "๐Ÿ“ง Email sent for Order ##{order.id}"
  end
end

order = Order.new(42)
order.add_observer(EmailNotifier.new)
order.place_order

What’s Happening?

  • Order includes the Observable module to gain observer capabilities.
  • add_observer registers an observer object.
  • When place_order is called:
    • changed marks the state as changed.
    • notify_observers(self) triggers the observer’s update method.
  • EmailNotifier reacts to the change โ€” in this case, it simulates sending an email.

๐Ÿงฉ Use this pattern when one change should trigger multiple actions โ€” like sending notifications, logging, or syncing data across objects.

Check: https://docs.ruby-lang.org/en/2.2.0/Observable.html

3. Decorator Pattern

class SimpleCoffee
  def cost
    2
  end
end

class MilkDecorator
  def initialize(coffee)
    @coffee = coffee
  end

  def cost
    @coffee.cost + 0.5
  end
end

coffee = MilkDecorator.new(SimpleCoffee.new)
puts coffee.cost  # => 2.5

Add responsibilities to objects dynamically without modifying their code.


๐Ÿ”„ 4. Strategy Pattern

The Strategy Pattern allows choosing an algorithm’s behaviour at runtime. This pattern is useful when you have multiple interchangeable ways to perform a task.

โœ… Example: Text Formatter Strategies

Let’s say you have a system that outputs text in different formats โ€” plain, HTML, or Markdown.

โŒ Before Using Strategy Pattern โ€” Hardcoded Conditional Formatting

class TextFormatter
  def initialize(format)
    @format = format
  end

  def format(text)
    case @format
    when :plain
      text
    when :html
      "<p>#{text}</p>"
    when :markdown
      "**#{text}**"
    else
      raise "Unknown format: #{@format}"
    end
  end
end

# Usage
formatter1 = TextFormatter.new(:html)
puts formatter1.format("Hello, World")       # => <p>Hello, World</p>

formatter2 = TextFormatter.new(:markdown)
puts formatter2.format("Hello, World")       # => **Hello, World**

โš ๏ธ Problems With This Approach

  • All formatting logic is stuffed into one method.
  • Adding a new format (like XML) means modifying this method (violates Open/Closed Principle).
  • Not easy to test or extend individual formatting behaviors.
  • Harder to maintain and violates SRP (Single Responsibility Principle).

This sets the stage perfectly to apply the Strategy Pattern, where each format becomes its own class with a clear responsibility.

Instead of writing if/else logic everywhere, use strategy objects:

# Strategy Interface
class TextFormatter
  def self.for(format)
    case format
    when :plain
      PlainFormatter.new
    when :html
      HtmlFormatter.new
    when :markdown
      MarkdownFormatter.new
    else
      raise "Unknown format"
    end
  end
end

# Concrete Strategies
class PlainFormatter
  def format(text)
    text
  end
end

class HtmlFormatter
  def format(text)
    "<p>#{text}</p>"
  end
end

class MarkdownFormatter
  def format(text)
    "**#{text}**"
  end
end

# Usage
def render_text(text, format)
  formatter = TextFormatter.for(format)
  formatter.format(text)
end

puts render_text("Hello, world", :html)     # => <p>Hello, world</p>
puts render_text("Hello, world", :markdown) # => **Hello, world**

๐Ÿ“Œ Why It’s Better

  • Adds new formats easily without changing existing code.
  • Keeps formatting logic isolated in dedicated classes.
  • Follows the Open/Closed Principle.

๐Ÿ’ณ Strategy Pattern in Rails: Payment Gateway Integration

Here’s a Rails-specific Strategy Pattern example. This example uses a service to handle different payment gateways (e.g., Stripe, PayPal, Razorpay), which are chosen dynamically based on configuration or user input.

Problem:

You want to process payments, but the actual logic differs depending on which gateway (Stripe, PayPal, Razorpay) is being used. Avoid if/else or case all over your controller or service.

โœ… Solution Using Strategy Pattern

# app/services/payment_processor.rb
class PaymentProcessor
  def self.for(gateway)
    case gateway.to_sym
    when :stripe
      StripeGateway.new
    when :paypal
      PaypalGateway.new
    when :razorpay
      RazorpayGateway.new
    else
      raise "Unsupported payment gateway"
    end
  end
end

# app/services/stripe_gateway.rb
class StripeGateway
  def charge(amount, user)
    # Stripe API integration here
    puts "Charging #{user.name} โ‚น#{amount} via Stripe"
  end
end

# app/services/paypal_gateway.rb
class PaypalGateway
  def charge(amount, user)
    # PayPal API integration here
    puts "Charging #{user.name} โ‚น#{amount} via PayPal"
  end
end

# app/services/razorpay_gateway.rb
class RazorpayGateway
  def charge(amount, user)
    # Razorpay API integration here
    puts "Charging #{user.name} โ‚น#{amount} via Razorpay"
  end
end

# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
  def create
    user = User.find(params[:user_id])
    gateway = params[:gateway] # e.g., 'stripe', 'paypal', etc.
    amount = params[:amount].to_i

    processor = PaymentProcessor.for(gateway)
    processor.charge(amount, user)

    render json: { message: \"Payment processed via #{gateway.capitalize}\" }
  end
end

โœ… Benefits in Rails Context

  • Keeps your controller slim and readable.
  • Each gateway integration is encapsulated in its own class.
  • Easy to test, extend, and maintain (open/closed principle).
  • Avoids future code smell like “Shotgun Surgery”.

โš ๏ธ What are Anti-Patterns?

Anti-patterns are poor programming practices or ineffective solutions that seem helpful at first but cause long-term issues like unmaintainable code or hidden bugs.

Common Ruby Anti-Patterns

๐Ÿงจ 1. God Object

A class that knows too much or does too much.

class UserManager
  def create_user
    # logic
  end

  def send_email
    # unrelated responsibility
  end

  def generate_report
    # another unrelated responsibility
  end
end

Fix: Follow the Single Responsibility Principle. Split into smaller, focused classes.


๐Ÿงจ Shotgun Surgery

Tiny changes require touching many different places in code.

# Example of Shotgun Surgery - Business rule spread across many files

# In order.rb
class Order
  def eligible_for_discount?
    user.vip? && total > 1000
  end
end

# In invoice.rb
class Invoice
  def apply_discount(order)
    if order.user.vip? && order.total > 1000
      # apply discount logic
    end
  end
end

# In email_service.rb
class EmailService
  def send_discount_email(order)
    if order.user.vip? && order.total > 1000
      # send congratulatory email
    end
  end
end

Here, the logic user.vip? && total > 1000 is repeated in multiple places. If the discount eligibility rules change (e.g., change the threshold to 2000 or add a new condition), you’ll have to update every occurrence.

โœ… Fix: Centralize the Logic

class DiscountPolicy
  def self.eligible?(order)
    order.user.vip? && order.total > 1000
  end
end

Now all files can use DiscountPolicy.eligible?(order), ensuring consistency and easier maintenance.


3. Spaghetti Code

Unstructured and difficult-to-follow code.

def calculate_discount(user, items)
  if user.vip?
    # deeply nested logic
    total = items.sum { |i| i.price }
    total * 0.2
  else
    if user.new_customer?
      total = items.sum { |i| i.price }
      total * 0.1
    else
      total = items.sum { |i| i.price }
      total * 0.05
    end
  end
end

This code is hard to read, hard to extend, and violates SRP (Single Responsibility Principle).

Fix: Break into smaller methods, use polymorphism or strategy patterns.

โœ… Refactored with Strategy Pattern

# Strategy Interface
class DiscountStrategy
  def self.for(user)
    if user.vip?
      VipDiscount.new
    elsif user.new_customer?
      NewCustomerDiscount.new
    else
      RegularDiscount.new
    end
  end
end

# Concrete Strategies
class VipDiscount
  def apply(items)
    total = items.sum(&:price)
    total * 0.2
  end
end

class NewCustomerDiscount
  def apply(items)
    total = items.sum(&:price)
    total * 0.1
  end
end

class RegularDiscount
  def apply(items)
    total = items.sum(&:price)
    total * 0.05
  end
end

# Usage
def calculate_discount(user, items)
  strategy = DiscountStrategy.for(user)
  strategy.apply(items)
end

๐ŸŽฏ Benefits

  • No nested conditionals
  • Easy to add new discount types (open/closed principle)
  • Each class has one responsibility
  • Testable and readable

๐Ÿ” How to Detect Anti-Patterns in Ruby Code

  1. Code Smells:
    • Long methods
    • Large classes
    • Repetition (DRY violations)
    • Deep nesting
  2. Code Review Checklist:
    • Is each class doing only one thing?
    • Can this method be broken down?
    • Are we repeating business logic?
    • Is the code testable?
  3. Use Static Analysis Tools:
    • Rubocop for style and complexity checks
    • Reek for code smells
    • Flog for measuring code complexity

๐Ÿ›  How to Refactor Anti-Patterns

  • Use Service Objects: Extract complex logic into standalone classes.
  • Apply Design Patterns: Choose the right pattern that matches your need (Strategy, Adapter, etc).
  • Keep Methods Small: Limit to a single task; ideally under 10 lines.
  • Write Tests First: Test-driven development (TDD) helps spot untestable designs.

๐ŸŽฏ Conclusion

Understanding design patterns and identifying anti-patterns is crucial for writing better Ruby code. While patterns guide you toward elegant solutions, anti-patterns warn you about common mistakes. With good design principles, automated tools, and thoughtful reviews, your Ruby codebase can remain healthy, scalable and developer-friendly.


Happy Designing Ruby! โœจ

Software Architectย Guide: Designing a RESTful API for a ๐ŸŒ Multi-Tenant Blogging Platform

Building a multi-tenant blogging platform requires thoughtful design of the API to ensure clarity, scalability, and security. In this post, we’ll explore a RESTful API design including versioning, nested resources, and authentication, using clear examples and best practices.


๐Ÿงฉ Understanding the Requirements

Before diving into endpoints, let’s break down what the platform supports:

  • Multiple tenants (e.g., organizations, teams)
  • Each tenant has users
  • Users can create blogs, and each blog has posts
  • Posts can have comments
  • Authentication is required

๐Ÿ“ Versioning

Weโ€™ll use URI-based versioning:

/api/v1/

This helps manage breaking changes cleanly.


๐Ÿ” Authentication

We’ll use token-based authentication (e.g., JWT or API keys). Each request must include:

Authorization: Bearer <token>

๐Ÿ“Œ Base URL

https://api.blogcloud.com/api/v1

๐Ÿ“š API Endpoint Design

๐Ÿ”ธ Tenants

Tenants are top-level entities.

  • GET /tenants โ€“ List all tenants (admin only)
  • POST /tenants โ€“ Create a new tenant
  • GET /tenants/:id โ€“ Show tenant details
  • PATCH /tenants/:id โ€“ Update tenant
  • DELETE /tenants/:id โ€“ Delete tenant

๐Ÿ”ธ Users (Scoped by tenant)

  • GET /tenants/:tenant_id/users โ€“ List users for tenant
  • POST /tenants/:tenant_id/users โ€“ Create user
  • GET /tenants/:tenant_id/users/:id โ€“ Show user
  • PATCH /tenants/:tenant_id/users/:id โ€“ Update user
  • DELETE /tenants/:tenant_id/users/:id โ€“ Delete user

๐Ÿ”ธ Blogs (Belong to users)

  • GET /tenants/:tenant_id/users/:user_id/blogs โ€“ List blogs
  • POST /tenants/:tenant_id/users/:user_id/blogs โ€“ Create blog
  • GET /tenants/:tenant_id/users/:user_id/blogs/:id โ€“ Show blog
  • PATCH /tenants/:tenant_id/users/:user_id/blogs/:id โ€“ Update blog
  • DELETE /tenants/:tenant_id/users/:user_id/blogs/:id โ€“ Delete blog

๐Ÿ”ธ Posts (Belong to blogs)

  • GET /blogs/:blog_id/posts โ€“ List posts
  • POST /blogs/:blog_id/posts โ€“ Create post
  • GET /blogs/:blog_id/posts/:id โ€“ Show post
  • PATCH /blogs/:blog_id/posts/:id โ€“ Update post
  • DELETE /blogs/:blog_id/posts/:id โ€“ Delete post

๐Ÿ”ธ Comments (Belong to posts)

  • GET /posts/:post_id/comments โ€“ List comments
  • POST /posts/:post_id/comments โ€“ Add comment
  • DELETE /posts/:post_id/comments/:id โ€“ Delete comment

โ“Question: what is the full url of comments?

No, the full URL for comments should not be:

https://api.blogcloud.com/api/v1/tenants/:tenant_id/users/:user_id/blogs/posts/:post_id/comments

That nesting is too deep and redundant, because:

  • By the time you’re at a post, you already implicitly know which blog/user/tenant it’s under (assuming proper authorization).
  • Posts have unique IDs across the system (or at least within blogs), so we donโ€™t need the entire hierarchy in every request.

โœ… Correct RESTful URL for Comments

If your post_id is unique (or unique within a blog), the cleanest design is:

https://api.blogcloud.com/api/v1/posts/:post_id/comments

or, if you prefer to keep blog_id context:

https://api.blogcloud.com/api/v1/blogs/:blog_id/posts/:post_id/comments

Use that second version only if post_id is not globally unique, and you need the blog context.

๐Ÿ” Recap of Comments Endpoints

ActionHTTP VerbEndpoint
List commentsGET/api/v1/posts/:post_id/comments
Create commentPOST/api/v1/posts/:post_id/comments
Delete commentDELETE/api/v1/posts/:post_id/comments/:id

๐Ÿง  Design Rule of Thumb

  • โœ… Keep URLs meaningful and shallow.
  • โŒ Don’t over-nest resources unless it’s needed to enforce scoping or clarify context.

๐Ÿ“ฅ Example: Create a Blog Post

Request:

POST /blogs/123/posts
Authorization: Bearer <token>
Content-Type: application/json

{
  "title": "Why REST APIs Still Matter",
  "body": "In this post, we explore the benefits of RESTful design..."
}

Response:

201 Created
{
  "id": 456,
  "title": "Why REST APIs Still Matter",
  "body": "In this post, we explore the benefits of RESTful design...",
  "created_at": "2025-07-03T10:00:00Z"
}


โœ… Best Practices Followed

  • Nesting: Resources are nested to show ownership (e.g., blogs under users).
  • Versioning: Prevents breaking old clients.
  • Consistency: Same verbs and JSON structure everywhere.
  • Authentication: Every sensitive request requires a token.

๐Ÿง  Final Thoughts

Designing a RESTful API for a multi-tenant app like a blogging platform requires balancing structure and simplicity. By properly scoping resources, using versioning, and enforcing auth, you build an API that’s powerful, secure, and easy to maintain.

Bonus Tip: Document your API using tools like Swagger/OpenAPI to make onboarding faster for new developers.

You are an awesome Architect ๐Ÿš€

Rails 8 App: Create an Academic software app using SQL without using ActiveRecord – Part 1 | users | products | orders

Let’s create a Rails 8 app which use SQL queries with raw SQL instead of ActiveRecord. Let’s use the full Rails environment with ActiveRecord for infrastructure, but bypass AR’s ORM features for pure SQL writing. Let me guide you through this step by step:

Step 1: Create the Rails App with ActiveRecord and PostgreSQL (skipping unnecessary components)

rails new academic-sql-software --database=postgresql --skip-action-cable --skip-jbuilder --skip-solid --skip-kamal

What we’re skipping and why:

  • –skip-action-cable: No WebSocket functionality needed
  • –skip-jbuilder: No JSON API views needed for our SQL practice app
  • –skip-solid: Skips Solid Cache and Solid Queue (we don’t need caching or background jobs)
  • –skip-kamal: No deployment configuration needed

What we’re keeping:

  • ActiveRecord: For database connection management and ActiveRecord::Base.connection.execute()
  • ActionController: For creating web interfaces to display our SQL query results
  • ActionView: For creating simple HTML pages to showcase our SQL learning exercises
  • PostgreSQL: Our database for practicing advanced SQL features

Why this setup is perfect for App with raw SQL:

  • Minimal Rails app focused on database interactions
  • Full Rails environment for development conveniences
  • ActiveRecord infrastructure without ORM usage
  • Clean setup without unnecessary overhead

=> Open config/application.rb and comment the following for now:

# require "active_job/railtie"
...
# require "active_storage/engine"
...
# require "action_mailer/railtie"
# require "action_mailbox/engine"
...
# require "action_cable/engine"

=> Open config/environments/development.rb config/environments/production.rb config/environments/test.rb comment action_mailer

๐Ÿค” Why I am using ActiveRecord (even though I don’t want the ORM):

  • Database Connection Management: ActiveRecord provides robust connection pooling, reconnection handling, and connection management
  • Rails Integration: Seamless integration with Rails console, database tasks (rails db:create, rails db:migrate), and development tools
  • Raw SQL Execution: We get ActiveRecord::Base.connection.execute() which is perfect for our raw SQL writing.
  • Migration System: Easy table creation and schema management with migrations (even though we’ll query with raw SQL)
  • Database Configuration: Rails handles database.yml configuration, environment switching, and connection setup
  • Development Tools: Access to Rails console for testing queries, database tasks, and debugging

Our Learning Strategy: We’ll use ActiveRecord’s infrastructure but completely bypass its ORM methods. Instead of Student.where(), we’ll use ActiveRecord::Base.connection.execute("SELECT * FROM students WHERE...")

Step 2: Navigate to the project directory

cd academic-sql-software

Step 3: Verify PostgreSQL setup

# Check if PostgreSQL is running
brew services list | grep postgresql
# or
pg_ctl status

Database Foundation: PostgreSQL gives us advanced SQL features:

  • Complex JOINs (INNER, LEFT, RIGHT, FULL OUTER)
  • Window functions (ROW_NUMBER, RANK, LAG, LEAD)
  • Common Table Expressions (CTEs)
  • Advanced aggregations and subqueries

Step 4: Install dependencies

bundle install

What this gives us:

  • pg gem: Pure PostgreSQL adapter (already included with --database=postgresql)
  • ActiveRecord: For connection management only
  • Rails infrastructure: Console, generators, rake tasks

Step 5: Create the PostgreSQL databases

โœ— rails db:create
Created database 'academic_sql_software_development'
Created database 'academic_sql_software_test

Our Development Environment:

  • Creates academic_sql_software_development and academic_sql_software_test
  • Sets up connection pooling and management
  • Enables us to use Rails console for testing queries: rails console then ActiveRecord::Base.connection.execute("SELECT 1")

Our Raw SQL Approach:

# We'll use this pattern throughout our app:
connection = ActiveRecord::Base.connection
result = connection.execute("SELECT s.name, t.subject FROM students s INNER JOIN teachers t ON s.teacher_id = t.id")

Why not pure pg gem:

  • Would require manual connection management
  • No Rails integration (no console, no rake tasks)
  • More boilerplate code for connection handling
  • Loss of Rails development conveniences

Why not pure ActiveRecord ORM:

  • We want to do SQL query writing, not ActiveRecord methods.
  • Need to understand database performance implications.
  • Want to practice complex queries that might be harder to express in ActiveRecord.

Step 6: Create Users table

mkdir -p db/migrate
class CreateUsers < ActiveRecord::Migration[8.0]
  def up
    # create users table
    execute <<~SQL
      CREATE TABLE users (
        id INT,
        username VARCHAR(200),
        email VARCHAR(150),
        phone_number VARCHAR(20)
      );
    SQL
  end

  def down
    execute <<~SQL
      DROP TABLE users;
    SQL
  end
end

class CreateOrders < ActiveRecord::Migration[8.0]
  def up
    # create table orders
    execute <<~SQL
    SQL
  end

  def down
    execute <<~SQL
    SQL
  end
end

execute <<~SQL is a Rails migration method that allows you to run raw SQL statements. Let me break it down:

Components:

  1. execute – A Rails migration method that executes raw SQL directly against the database
  2. <<~SQL – Ruby’s “squiggly heredoc” syntax for multi-line strings that automatically strips leading whitespace (read: https://www.rubyguides.com/2018/11/ruby-heredoc/)

Usage:

class SomeMigration < ActiveRecord::Migration[8.0]
  def change
    execute <<~SQL
      CREATE INDEX CONCURRENTLY idx_users_email_lower 
      ON users (LOWER(email));
    SQL
  end
end

Why use it?

  • Database-specific features: When you need PostgreSQL-specific syntax, MySQL features, etc.
  • Complex SQL: For operations that Rails DSL doesn’t support easily
  • Performance: Direct SQL can sometimes be more efficient
  • Raw SQL requirements: When you specifically need to write SQL (as mentioned in our requirement)

Example for creating a users table with raw SQL:

class CreateUsers < ActiveRecord::Migration[8.0]
  def up
    execute <<~SQL
      CREATE TABLE users (
        id BIGSERIAL PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
      );

      CREATE UNIQUE INDEX idx_users_email ON users(email);
    SQL
  end

  def down
    execute <<~SQL
      DROP TABLE IF EXISTS users;
    SQL
  end
end

The <<~SQL heredoc ends when it encounters the closing SQL keyword, and the ~ strips indentation so your SQL can be properly formatted within the Ruby code.

Q) ๐Ÿค” Is it a best practise to repeat the database constraints in model validation in Rails? DB level vs App level? or both?

Best Practice: Use BOTH ๐ŸŽฏ

Why both levels are recommended:

Database Level (Last Line of Defense)

-- Database constraints
price DECIMAL(10,2) NOT NULL CHECK (price > 0),
category product_category NOT NULL,
title VARCHAR(250) NOT NULL

Pros:

  • โœ… Data integrity guarantee – No bad data can enter, ever
  • โœ… Performance – Database enforces constraints efficiently
  • โœ… Bulletproof – Protects against bulk operations, direct SQL, data imports
  • โœ… Concurrency safe – Prevents race conditions
  • โœ… Multi-application protection – If other apps access same DB

Application Level (User Experience)

validates :price, presence: true, numericality: { greater_than: 0 }
validates :category, inclusion: { in: %w[men women kids infants] }

Pros:

  • โœ… User-friendly errors – “Price must be greater than 0” vs “CHECK constraint violated”
  • โœ… Better UX – Validation before form submission
  • โœ… Easier testing – Can unit test validations
  • โœ… Conditional logic – Complex business rules
  • โœ… Framework features – Callbacks, custom validators

Real-world scenarios where each matters:

Database saves you when:

# Bulk operations bypass Rails validations
Product.update_all(price: -10)  # DB constraint prevents this

# Direct SQL injection attempts
# DB constraints are your last line of defense

App validations save you when:

# User gets friendly error instead of:
# PG::CheckViolation: ERROR: new row violates check constraint
@product = Product.new(price: -5)
@product.valid? # => false
@product.errors.full_messages # => ["Price must be greater than 0"]

Practical Implementation:

class Product < ApplicationRecord
  # App-level validations for UX
  validates :title, presence: true, length: { maximum: 250 }
  validates :price, presence: true, numericality: { greater_than: 0 }
  validates :category, inclusion: { in: %w[men women kids infants] }

  # Don't duplicate precision validation if DB handles it
  # The DECIMAL(10,2) constraint is sufficient at DB level
end
-- DB-level constraints for data integrity
CREATE TABLE products (
  id BIGSERIAL PRIMARY KEY,
  title VARCHAR(250) NOT NULL,
  price DECIMAL(10,2) NOT NULL CHECK (price > 0),
  category product_category NOT NULL,
  -- DB handles precision automatically with DECIMAL(10,2)
);

What NOT to duplicate:

  • โŒ Precision constraintsDECIMAL(10,2) handles this perfectly
  • โŒ Data type validation – DB enforces INTEGER, BOOLEAN, etc.
  • โŒ Complex regex patterns – Better handled in app layer

Conclusion:

Use both, but strategically:

  • Database: Core data integrity, type constraints, foreign keys
  • Application: User experience, business logic, conditional rules
  • Don’t over-duplicate simple type/precision constraints that DB handles well

This approach gives you belt and suspenders protection with optimal user experience.

to be continued … ๐Ÿš€