ActiveRecord

Guide Rails ActiveRecord migrations, associations, query optimization, and validations.

11|Updated Jun 19, 2013
One-click install
npx skills add https://github.com/MadBomber/experiments --skill activerecord-madbomber
Or copy as Structured Prompt for Agent
Please help me install this Agent Skill.
Skill: ActiveRecord
Source: https://github.com/MadBomber/experiments/tree/main/ai_misc/skills/hoblin-activerecord
Command: npx skills add https://github.com/MadBomber/experiments --skill activerecord-madbomber

SYSTEM DOCUMENTATION & REQUIREMENTS

💡 This Skill includes scripts (resource) and references (resource) components.

What problem does it solve?

This Skill simplifies complex database operations within Rails applications, making it easier to manage data integrity and performance.

Core Features & Use Cases

  • Migrations: Write and manage database schema changes safely.
  • Associations: Define relationships like belongs_to, has_many, and has_many :through.
  • Query Optimization: Prevent N+1 queries using includes, preload, and eager_load.
  • Use Case: You need to add a new column to your users table, ensure it's always present, and create a unique index on it for faster lookups.

Quick Start

Use the ActiveRecord skill to add a status column of type string to the orders table with a default value of 'pending'.

Frequently Asked Questions about ActiveRecord

High-intent search queries and answers about installing and using this skill.

FAQPage Schema
How do I prevent N+1 queries in Rails ActiveRecord?

Prevent N+1 queries in Rails ActiveRecord by using eager loading methods like `includes`, `preload`, and `eager_load` to fetch associated records in fewer database queries, significantly optimizing application performance.

What is the best way to add a new database column in Rails migrations?

Add a database column in Rails migrations by defining the schema change with safe defaults, such as adding a `status` string column with a default value of 'pending', and creating a unique index for faster lookups.

How do I define associations like has_many and belongs_to in ActiveRecord?

Define associations in ActiveRecord using macros like `belongs_to`, `has_many`, and `has_many :through` to establish relationships between models, ensuring data integrity and simplifying complex database interactions.

When should I use counter caches in Rails?

Use counter caches in Rails when you frequently need to count associated records, such as comments on a post; this caches the count number directly on the parent model to avoid expensive database count queries.

Does ActiveRecord support conditional callbacks for validations?

Yes, ActiveRecord supports conditional callbacks for validations, allowing you to trigger logic dynamically based on specific conditions or states within your Rails application, ensuring data integrity only when necessary.