rails

ruby
class CreateComments < ActiveRecord::Migration[6.1]
  def change
    create_table :comments do |t|
      t.references :commentable, polymorphic: true, null: false
      t.references :author, null: false, foreign_key: { to_table: :users }
      t.text :body, null: false

Polymorphic associations for flexible relationships

rails activerecord database
by Alex Kumar 3 tabs
ruby
class DashboardMetrics
  include ActiveModel::Model

  attr_reader :account

  def initialize(account)

Expiring Dashboard Fragment Caches with a Versioned Composite Cache Key in Rails

rails caching fragment-caching
by codesnips 3 tabs
ruby
class AddressForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :line1, :string
  attribute :line2, :string

Rails Nested Address Form Object With Aggregated ActiveModel Errors

rails activemodel form-object
by codesnips 3 tabs
ruby
class CommentsController < ApplicationController
  before_action :set_post

  def new
    @comment = @post.comments.build
  end

Turbo Stream form errors: replace only the form frame

rails turbo hotwire
by codesnips 4 tabs
ruby
module RequestStore
  def self.store
    Thread.current[:request_store] ||= {}
  end

  def self.fetch(key)

Hot Path Memoization (within request only)

rails performance memoization
by codesnips 4 tabs
erb
<%= link_to 'Newest', posts_path(sort: 'new'), data: { turbo_frame: 'results', turbo_action: 'replace' } %>
<%= link_to 'Popular', posts_path(sort: 'popular'), data: { turbo_frame: 'results', turbo_action: 'replace' } %>

Hotwire-friendly “sort by” links that replace only the list

rails hotwire turbo
by Henry Kim 2 tabs
ruby
class ImportRun < ApplicationRecord
  enum status: { pending: 0, running: 1, completed: 2, failed: 3 }

  def percent
    return 0 if total.to_i.zero?
    [(processed.to_f / total * 100).round, 100].min

Live Turbo Streams Progress Bar for a Long Rails Job

rails turbo-streams hotwire
by codesnips 4 tabs
ruby
class LikesController < ApplicationController
  before_action :set_post

  def create
    @like = current_user.likes.create!(post: @post)
    respond(liked: true)

Turbo Streams: swap a button state and counter in one response

rails hotwire turbo
by codesnips 4 tabs
ruby
class AddSlugToPosts < ActiveRecord::Migration[7.1]
  def change
    add_column :posts, :slug, :string, null: false
    add_index :posts, :slug, unique: true
  end
end

Database-Backed Unique Slugs with Retry

rails postgres slugs
by codesnips 4 tabs
ruby
module Posts
  class CreateService
    def initialize(author:, params:)
      @author = author
      @params = params
    end

Rails service objects for business logic

rails architecture service-objects
by Maya Patel 2 tabs
ruby
namespace :cleanup do
  desc "Enqueue a job to purge expired sessions"
  task expired_sessions: :environment do
    job = ExpiredSessionCleanupJob.perform_later
    Rails.logger.info("[cleanup:expired_sessions] enqueued job #{job.job_id}")
  end

Recurring Cleanup with a Rake Task and an Idempotent Active Job in Rails

rails background-jobs active-job
by codesnips 4 tabs
ruby
Rails.application.routes.draw do
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :articles, only: [:index, :show, :create, :update, :destroy]
      resources :sessions, only: [:create]
    end

Versioned JSON API Namespace in Rails With a Shared Base Controller

rails api versioning
by codesnips 3 tabs