Ruby Rails 标志

Ruby Rails

社区
j4flmao
ruby-rails

Use this skill when building Ruby on Rails applications — MVC, ActiveRecord, service objects, API mode, background jobs, and testing. This skill enforces: thin controllers, service objects for business logic, ActiveRecord query best practices, Rails API mode conventions, and RSpec testing patterns. Requires Rails 7+ and Ruby 3.1+. Do NOT use for: Sinatra, Rack apps, Hanami, or non-Rails Ruby projects.

概览

发布者j4flmao
代码仓库agent-skills
技能名称ruby-rails
星标数
41
复刻数
6
附带文件
8
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 8 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 j4flmao 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Ruby Rails AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/ruby/rails
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/ruby/rails .claude/skills/ruby-rails
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Ruby Rails,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Ruby Rails。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Ruby Rails 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Ruby on Rails

Purpose

Build Rails applications with clean MVC separation, service objects, ActiveRecord optimization, API mode conventions, Sidekiq background jobs, and RSpec testing patterns.

Agent Protocol

Trigger

User request includes: Rails, Ruby on Rails, Rails API, ActiveRecord, Rails controller, Rails model, Rails service, Rails job, Rails spec, Rails migration.

Input Context

  • Rails version (7.0+, 7.1+)
  • Ruby version (3.1+, 3.2+, 3.3+)
  • Database (PostgreSQL, MySQL, SQLite)
  • Mode (API-only, full MVC)
  • Auth (Devise, JWT, OAuth)
  • Background jobs (Sidekiq, GoodJob, Solid Queue)

Output Artifact

Controller, model, service object, job class, migration, RSpec test.

Response Format

Produce artifact directly. No preamble, no postamble, no explanations.

Completion Criteria

  • Controller delegates to service objects
  • ActiveRecord model with scopes, validations, associations
  • Service object encapsulates business logic
  • Background job with retry configuration
  • Request spec covers CRUD with JSON
  • Migration with proper indexes

Max Response Length

4096 tokens

Architecture Decision Trees

Service Objects vs PORO Models vs Concerns

CriterionService ObjectFat ModelConcern
Business logic locationapp/services/app/models/app/concerns/
TestabilityEasy (isolated)Moderate (needs DB)Moderate
ReusabilityHigh (injectable)Low (AR callbacks)Medium (mixed into models)
Complexity per unitLowHigh (grows unbound)Medium
Rails conventionsNo (manual)Yes (default)Yes (Rails 4+)

Decision: Complex business rules → Service Object. Simple validations/scopes → Model. Cross-model behavior → Concern.

ActiveRecord vs ActiveRecord::Base vs Sequel

CriterionActiveRecordSequelROM.rb
Rails integrationNativeAdapterAdapter
PerformanceModerateHighHigh
Query interfaceRich DSLSequel DSLRelation-based
AssociationsDeclarativeDeclarativeExplicit
Migration systemBuilt-inBuilt-inStandalone

Decision: Rails project → ActiveRecord. Heavy data pipeline → Sequel. Hexagonal/clean arch → ROM.rb.

Workflow

Step 1: Rails API Setup

bash
rails new my_api --api --database=postgresql --skip-test
cd my_api

Step 2: Directory Conventions (API Mode)

app/
  controllers/
    application_controller.rb
    api/
      v1/
        users_controller.rb
        orders_controller.rb
  models/
    user.rb
    order.rb
  services/
    users/
      create_service.rb
      update_service.rb
    orders/
      place_order_service.rb
  serializers/
    user_serializer.rb
    order_serializer.rb
  jobs/
    process_order_job.rb
  policies/
    user_policy.rb
config/
  routes.rb
spec/
  requests/
    users_spec.rb
  services/
    users/
      create_service_spec.rb

Step 3: Routes

ruby
# config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :users, only: [:index, :show, :create, :update, :destroy]
      resources :orders, only: [:index, :show, :create]
    end
  end
end

Step 4: ActiveRecord Model

ruby
# app/models/user.rb
class User < ApplicationRecord
  # Enums
  enum :role, { user: 0, admin: 1, moderator: 2 }, default: :user

  # Validations
  validates :email, presence: true, uniqueness: { case_sensitive: false },
                    format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :name, presence: true, length: { minimum: 2, maximum: 100 }

  # Scopes
  scope :active, -> { where(active: true) }
  scope :by_role, ->(role) { where(role: role) }
  scope :recent, -> { order(created_at: :desc) }
  scope :search, ->(query) {
    where('name ILIKE :q OR email ILIKE :q', q: "%#{sanitize_sql_like(query)}%")
  }

  # Associations
  has_many :orders, dependent: :destroy

  # Callbacks
  after_create :send_welcome_email

  private

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

# db/migrate/xxxx_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
  def change
    create_table :users, id: :uuid do |t|
      t.string :name, null: false
      t.string :email, null: false
      t.integer :role, default: 0, null: false
      t.boolean :active, default: true, null: false
      t.timestamps
    end
    add_index :users, :email, unique: true
    add_index :users, :role
    add_index :users, [:active, :role]
  end
end

Step 5: Serializer

ruby
# app/serializers/user_serializer.rb
class UserSerializer
  include JSONAPI::Serializer

  attributes :name, :email, :role, :active
  attribute :created_at do |user|
    user.created_at.iso8601
  end
  has_many :orders, serializer: OrderSerializer
end

Step 6: Service Object

ruby
# app/services/users/create_service.rb
module Users
  class CreateService < ApplicationService
    attr_reader :params

    def initialize(params)
      @params = params
    end

    def call
      validate_email_uniqueness!
      user = User.new(user_attributes)

      ActiveRecord::Base.transaction do
        user.save!
        create_audit_log(user)
      end

      Result.success(user)
    rescue ActiveRecord::RecordInvalid => e
      Result.failure(e.record.errors.full_messages)
    rescue ActiveRecord::RecordNotUnique
      Result.failure(['Email has already been taken'])
    end

    private

    def user_attributes
      {
        name: params[:name],
        email: params[:email].downcase.strip,
        role: params[:role] || :user,
      }
    end

    def validate_email_uniqueness!
      if User.exists?(email: params[:email])
        raise ActiveRecord::RecordNotUnique, "Email taken"
      end
    end

    def create_audit_log(user)
      AuditLog.create!(action: 'user_created', target: user)
    end
  end
end

# app/services/application_service.rb
class ApplicationService
  Result = Struct.new(:success?, :data, :errors, keyword_init: true)

  def self.call(...)
    new(...).call
  end
end

Step 7: Thin Controller

ruby
# app/controllers/api/v1/users_controller.rb
module Api
  module V1
    class UsersController < ApplicationController
      before_action :authenticate_user!
      before_action :set_user, only: [:show, :update, :destroy]

      def index
        users = User.active.recent.page(params[:page]).per(params[:per_page] || 20)
        render json: UserSerializer.new(users).serializable_hash
      end

      def show
        render json: UserSerializer.new(@user).serializable_hash
      end

      def create
        result = Users::CreateService.call(user_params.to_h)

        if result.success?
          render json: UserSerializer.new(result.data).serializable_hash, status: :created
        else
          render json: { errors: result.errors }, status: :unprocessable_entity
        end
      end

      def update
        result = Users::UpdateService.call(@user, user_params.to_h)

        if result.success?
          render json: UserSerializer.new(result.data).serializable_hash
        else
          render json: { errors: result.errors }, status: :unprocessable_entity
        end
      end

      def destroy
        @user.update!(active: false)
        head :no_content
      end

      private

      def set_user
        @user = User.find(params[:id])
      end

      def user_params
        params.permit(:name, :email, :role)
      end
    end
  end
end

Step 8: Background Job

ruby
# app/jobs/process_order_job.rb
class ProcessOrderJob < ApplicationJob
  queue_as :default
  retry_on StandardError, attempts: 3, wait: :exponentially_longer
  discard_on ActiveRecord::RecordNotFound

  def perform(order_id)
    order = Order.find(order_id)
    InventoryService.new.reserve_items(order)
    order.update!(status: :processing)
    OrderMailer.confirmation(order).deliver_later
  rescue InsufficientInventoryError => e
    order.update!(status: :failed, failure_reason: e.message)
    raise
  end
end

Implementation Patterns

Pattern: Query Object

ruby
# app/queries/user_orders_query.rb
class UserOrdersQuery
  def initialize(relation = Order.all)
    @relation = relation
  end

  def by_user(user_id)
    @relation.where(user_id: user_id)
  end

  def with_status(status)
    @relation.where(status: status)
  end

  def recent_first
    @relation.order(created_at: :desc)
  end

  def paginated(page:, per_page: 20)
    @relation.page(page).per(per_page)
  end
end

Pattern: Policy Object

ruby
# app/policies/user_policy.rb
class UserPolicy
  def initialize(current_user, target_user)
    @current_user = current_user
    @target_user = target_user
  end

  def show?
    @current_user == @target_user || @current_user.admin?
  end

  def update?
    @current_user == @target_user || @current_user.admin?
  end

  def destroy?
    @current_user.admin?
  end
end

Production Considerations

Database Performance

  • Add id: :uuid for distributed systems, :bigint for sequential
  • Index all foreign keys and frequently queried columns
  • Use includes(:associations) for eager loading — never lazy load in views
  • Use pluck for single column queries instead of loading full records
  • Use find_each/in_batches for large data processing (not all.each)
  • Connection pooling: pool: ENV.fetch('RAILS_MAX_THREADS', 5) in database.yml

Sidekiq Configuration

ruby
# config/sidekiq.yml
:concurrency: 5
:queues:
  - critical
  - default
  - low
:schedule:
  cleanup_job:
    cron: "0 0 * * *"
    class: CleanupJob

Anti-Patterns

Anti-PatternWhyFix
Callbacks for cross-model logicHidden dependencies, hard to testService objects
Fat models with > 200 linesSRP violation, unmaintainableExtract service/query objects
N+1 queries in serializers100+ queries per responseincludes in controller
all.each on large tablesMemory exhaustionfind_each or in_batches
Logic in before_actionHard to trace, testPolicy objects or direct checks
Strong params in controllerRepetitive across actionsPermitted params in service object

Security Considerations

  • has_secure_password for bcrypt — never store plain passwords
  • Devise or JWT for auth — never custom token implementation
  • Strong parameters in every controller — prevent mass assignment
  • before_action :authenticate_user! on protected controllers
  • SQL injection: ActiveRecord is safe (parameterized), but where("name = '#{param}'") is not
  • config.force_ssl = true in production
  • CORS gem (rack-cors) for API mode — restrict origins
  • Rate limiting with rack-attack gem

Testing Strategies

ruby
# spec/requests/api/v1/users_spec.rb
RSpec.describe 'Users API', type: :request do
  describe 'POST /api/v1/users' do
    let(:valid_params) { { name: 'John', email: 'john@test.com' } }

    it 'creates a new user' do
      post '/api/v1/users', params: valid_params, as: :json
      expect(response).to have_http_status(:created)
      expect(json['data']['attributes']['email']).to eq('john@test.com')
    end

    it 'returns 422 with invalid params' do
      post '/api/v1/users', params: { name: '' }, as: :json
      expect(response).to have_http_status(:unprocessable_entity)
    end
  end
end

Use factory_bot_rails for test data. Use shoulda-matchers for model specs. Use database_cleaner for test isolation. Use webmock/vcr for external HTTP. Use rspec-sidekiq for job testing.

Rules

  • Controllers are thin — one line of business logic per action.
  • Service objects in app/services/ — call with .call(params) returning Result.
  • ActiveRecord models under 150 lines — validations, scopes, associations only.
  • Serializers via jsonapi-serializer or active_model_serializers.
  • Background jobs have retry_on with limits and discard_on for known failures.
  • All database migrations have add_index for foreign keys and filtered columns.
  • API mode Rails — no views, no cookies (token-based auth).

References

  • references/rails-active-record.md — ActiveRecord Best Practices
  • references/rails-api-conventions.md — Rails API Conventions
  • references/rails-api-design.md — Rails API Design
  • references/rails-background-jobs.md — Background Jobs
  • references/rails-performance-tuning.md — Performance Tuning
  • references/rails-performance.md — Rails Performance
  • references/rails-security.md — Rails Security
  • references/rails-testing.md — Testing Rails Applications

Handoff

Hand off to backend/universal/api-response/SKILL.md for API response formatting or backend/universal/backend-testing/SKILL.md for test patterns.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Ruby Rails AI 技能有什么作用?

Use this skill when building Ruby on Rails applications — MVC, ActiveRecord, service objects, API mode, background jobs, and testing. This skill enforces: thin controllers, service objects for business logic, ActiveRecord query best practices, Rails API mode conventions, and RSpec testing patterns. Requires Rails 7+ and Ruby 3.1+. Do NOT use for: Sinatra, Rack apps, Hanami, or non-Rails Ruby projects.

为什么在 TypingMind 中使用 Ruby Rails?

因为您只需安装一次,就能搭配任何模型使用。Ruby Rails 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Ruby Rails?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/j4flmao/agent-skills/tree/main/skills/backend/ruby/rails。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Ruby Rails?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Ruby Rails 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Ruby Rails 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Ruby Rails AI 技能免费吗?

是的。j4flmao 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇