Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

rails-active-record-patterns

БесплатноБез исполняемых скриптовНе проверен

Use when active Record patterns including models, associations, queries, validations, and callbacks.

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Rails Active Record Patterns

Master Active Record patterns for building robust Rails models with proper associations, validations, scopes, and query optimization.

Overview

Active Record is Rails' Object-Relational Mapping (ORM) layer that connects model classes to database tables. It implements the Active Record pattern, where each object instance represents a row in the database and includes both data and behavior.

Installation and Setup

Creating Models

# Generate a model with migrations
rails generate model User name:string email:string:uniq

# Generate model with associations
rails generate model Post title:string body:text user:references

# Run migrations
rails db:migrate

Database Configuration

# config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: myapp_production
  username: myapp
  password: <%= ENV['MYAPP_DATABASE_PASSWORD'] %>

Core Patterns

1. Basic Model Definition

# app/models/user.rb
class User < ApplicationRecord
  # Validations
  validates :email, presence: true, uniqueness: true,
    format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :name, presence: true, length: { minimum: 2, maximum: 50 }

  # Callbacks
  before_save :normalize_email
  after_create :send_welcome_email

  # Scopes
  scope :active, -> { where(active: true) }
  scope :recent, -> { order(created_at: :desc).limit(10) }

  private

  def normalize_email
    self.email = email.downcase.strip
  end

  def send_welcome_email
    UserMailer.welcome(self).deliver_later
  end
end

2. Associations

# app/models/user.rb
class User < ApplicationRecord
  # One-to-many
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy

  # Many-to-many through join table
  has_many :memberships, dependent: :destroy
  has_many :organizations, through: :memberships

  # Has-one
  has_one :profile, dependent: :destroy

  # Polymorphic association
  has_many :images, as: :imageable, dependent: :destroy
end

# app/models/post.rb
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
  has_many :commenters, through: :comments, source: :user

  # Counter cache
  belongs_to :user, counter_cache: true
end

# app/models/organization.rb
class Organization < ApplicationRecord
  has_many :memberships, dependent: :destroy
  has_many :users, through: :memberships
end

# app/models/membership.rb
class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :organization

  enum role: { member: 0, admin: 1, owner: 2 }
end

3. Advanced Queries

# app/models/post.rb
class Post < ApplicationRecord
  # Scopes with arguments
  scope :by_author, ->(user_id) { where(user_id: user_id) }
  scope :published_after, ->(date) { where('published_at > ?', date) }
  scope :with_tag, ->(tag) { joins(:tags).where(tags: { name: tag }) }

  # Class methods for complex queries
  def self.popular(threshold = 100)
    where('views_count >= ?', threshold)
      .order(views_count: :desc)
  end

  def self.search(query)
    where('title ILIKE ? OR body ILIKE ?', "%#{query}%", "%#{query}%")
  end

  # Query with joins and includes
  def self.with_user_and_comments
    includes(:user, comments: :user)
      .order(created_at: :desc)
  end
end

# Usage
Post.published_after(1.week.ago)
  .by_author(current_user.id)
  .with_tag('rails')
  .popular(50)

4. Validations

# app/models/user.rb
class User < ApplicationRecord
  # Presence validation
  validates :email, :name, presence: true

  # Uniqueness validation
  validates :email, uniqueness: { case_sensitive: false }

  # Format validation
  validates :username, format: {
    with: /\A[a-z0-9_]+\z/,
    message: "only allows lowercase letters, numbers, and underscores"
  }

  # Length validation
  validates :bio, length: { maximum: 500 }
  validates :password, length: { minimum: 8 }, if: :password_required?

  # Numericality validation
  validates :age, numericality: {
    only_integer: true,
    greater_than_or_equal_to: 18,
    less_than: 120
  }

  # Custom validation
  validate :email_domain_allowed

  private

  def email_domain_allowed
    return if email.blank?

    domain = email.split('@').last
    unless ALLOWED_DOMAINS.include?(domain)
      errors.add(:email, "domain #{domain} is not allowed")
    end
  end

  def password_required?
    new_record? || password.present?
  end
end

5. Callbacks

# app/models/post.rb
class Post < ApplicationRecord
  # Before callbacks
  before_validation :normalize_title
  before_save :calculate_reading_time
  before_create :generate_slug

  # After callbacks
  after_create :notify_followers
  after_update :clear_cache, if: :saved_change_to_body?
  after_destroy :cleanup_attachments
Полный SKILL.md на GitHub

Установить rails-active-record-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Edit
Grep
Glob
Bash

FAQ

Что делает скилл rails-active-record-patterns?

Use when active Record patterns including models, associations, queries, validations, and callbacks.

Как установить скилл rails-active-record-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rails-active-record-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить rails-active-record-patterns с