ruby
module Api
  module V1
    class PostsController < BaseController
      def index
        # Eager load author and recent comments with their authors
        posts = Post.published

N+1 prevention with includes and preload

rails activerecord performance
by Alex Kumar 1 tab
ruby
class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id

  validates :email, presence: true,
                    uniqueness: { case_sensitive: false },
                    format: { with: URI::MailTo::EMAIL_REGEXP }

Model validations for data integrity

rails activerecord validation
by Alex Kumar 1 tab
yaml
production:
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS", 5) %>
  timeout: 5000
  checkout_timeout: 5

Database connection pooling configuration

rails database performance
by Alex Kumar 2 tabs
ruby
module ApiRequestLogger
  extend ActiveSupport::Concern

  included do
    around_action :log_api_request
  end

API request logging for debugging and analytics

rails logging observability
by Alex Kumar 1 tab
ruby
class AddCommentsCountToPosts < ActiveRecord::Migration[6.1]
  def up
    add_column :posts, :comments_count, :integer, default: 0, null: false

    # Populate existing counts
    Post.find_each do |post|

Counter cache for association counts

rails performance activerecord
by Alex Kumar 2 tabs
ruby
class AddLockVersionToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :lock_version, :integer, default: 0, null: false
  end
end

Optimistic locking for concurrent updates

rails database concurrency
by Alex Kumar 2 tabs
ruby
class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :excerpt, :body, :published_at, :views, :likes_count, :comments_count

  attribute :can_edit, if: :current_user_can_edit?

  belongs_to :author, serializer: UserSummarySerializer

Serializers with ActiveModel::Serializers

rails api serialization
by Alex Kumar 2 tabs
ruby
class PopularPostsQuery
  def initialize(relation = Post.all)
    @relation = relation
  end

  def call(timeframe: 7.days, min_views: 100, limit: 20)

Query objects for complex ActiveRecord queries

rails activerecord patterns
by Alex Kumar 2 tabs
ruby
class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id, dependent: :destroy

  before_validation :normalize_email
  before_create :generate_auth_token
  after_create :send_welcome_email

ActiveRecord callbacks for lifecycle hooks

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class PostsController < BaseController
      before_action :authenticate_user!

      def create

Strong parameters for mass assignment protection

rails security api
by Alex Kumar 1 tab
ruby
class TransferFundsService
  def initialize(from_account:, to_account:, amount:)
    @from_account = from_account
    @to_account = to_account
    @amount = amount
  end

Database transactions for data consistency

rails database activerecord
by Alex Kumar 1 tab
ruby
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins_list = if Rails.env.production?
                     ENV['CORS_ALLOWED_ORIGINS']&.split(',') || []
                   else
                     'localhost:3000', 'localhost:5173', /127\.0\.0\.1:\d+/

CORS configuration for cross-origin API requests

rails api security
by Alex Kumar 1 tab