ruby

Rails Background Jobs with ActiveJob and Sidekiq

Background jobs improve performance by offloading time-consuming tasks like sending emails. This snippet uses ActiveJob with Sidekiq to send a welcome email asynchronously. The SendWelcomeEmailJob finds the user and triggers the mailer, while the User

Rails ActiveStorage: Attach and Display Images Easily

This snippet enables a User model to attach an avatar image with just has_one_attached :avatar. The view logic checks if an avatar exists and displays it using image_tag. This approach avoids complex file storage logic, letting Rails handle uploads se

Ruby on Rails: Storing and Querying JSON Data in PostgreSQL

This snippet uses PostgreSQL’s JSONB column to store flexible metadata for orders, making it easy to store dynamic attributes without schema changes. The scopes allow efficient filtering using native SQL JSON functions. The update_metadata method enab

Ruby on Rails Concern for Soft Deletable Records Without Losing Data

Generating Secure One-Time Tokens Without Devise in Ruby on Rails

This snippet lets you generate secure, one-time-use tokens for password resets without Devise. It stores the token in the database, checks its validity, and clears it after use. The send_reset_link action sends the reset link, and the reset action ver

Using Rails Callbacks to Auto-Generate a Unique Slug

Slugs are essential for SEO-friendly URLs and user-friendly navigation, and this snippet ensures each article automatically generates a unique slug based on its title. Using the before_create callback, we transform the title into a URL-safe format usi

Rails Enum for Clean and Readable Status Management

Managing statuses in a Rails model can become messy with hardcoded values, but enums provide a clean and readable way to handle them. This snippet shows how to define an enum in an Order model, making it easy to reference statuses with descriptive sym