Token导航 LogoToken导航

Agent Skill · 研究检索

rails-action-controller-patterns(Rails action controller 模式)

rails-action-controller-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

rails-action-controller-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证为 MIT,第三方扫描有未通过项,按安装量在研究检索类的 73,675 个 Skill 里排第 57,638。

总安装 428周安装 18GitHub Stars 142下载 150核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rails-action-controller-patterns(Rails action controller 模式)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/rails-action-controller-patterns
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill rails-action-controller-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill rails-action-controller-patterns

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于查找和筛选 Rails 应用中控制器相关的最佳实践与模式示例。适合在重构或学习 MVC 结构时参考已有实现方式。通过 GitHub 安装,可结合具体项目路径定位相关文件。注意不同 Rails 版本间可能存在语法差异,需做兼容性检查。建议对照官方文档验证所引用模式的适用性。

rails-action-controller-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/rails-action-controller-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/thebushidocollective/han --skill rails-action-…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

rails-action-controller-patterns 怎么安装?

在终端执行 npx skills add https://github.com/thebushidocollective/han --skill rails-action-controller…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

rails-action-controller-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

rails-action-controller-patterns 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

rails-action-controller-patterns 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

rails-action-controller-patterns 用的人多吗?

公开数据是累计安装 428 次,近一周安装 18 次,下载 150 次,GitHub 142 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

rails-action-controller-patterns 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。

先想清楚的地方

  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
rails-action-controller-patterns

Rails action controller 模式 · 本页

428142需要联网MIT未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Rails Action Controller Patterns

Master Action Controller patterns for building robust Rails controllers with proper routing, filters, parameter handling, and RESTful design.

Overview

Action Controller is the component that handles web requests in Rails. It processes incoming requests, interacts with models, and renders responses. Controllers follow the MVC pattern and implement REST conventions by default.

Installation and Setup

Generating Controllers

# Generate a resource controller
rails generate controller Posts index show new create edit update destroy

# Generate a namespaced controller
rails generate controller Admin::Posts index show

# Generate an API-only controller
rails generate controller Api::V1::Posts --no-helper --no-assets

Routing Configuration

# config/routes.rb
Rails.application.routes.draw do
  # RESTful resources
  resources :posts

  # Nested resources
  resources :posts do
    resources :comments
  end

  # Namespaced routes
  namespace :admin do
    resources :posts
  end

  # Custom routes
  get 'about', to: 'pages#about'
  root 'posts#index'
end

Core Patterns

1. Basic Controller Structure

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authorize_post, only: [:edit, :update, :destroy]

  # GET /posts
  def index
    @posts = Post.includes(:user)
                 .order(created_at: :desc)
                 .page(params[:page])
  end

  # GET /posts/:id
  def show
    @comments = @post.comments.includes(:user)
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # POST /posts
  def create
    @post = current_user.posts.build(post_params)

    if @post.save
      redirect_to @post, notice: 'Post was successfully created.'
    else
      render :new, status: :unprocessable_entity
    end
  end

  # GET /posts/:id/edit
  def edit
  end

  # PATCH/PUT /posts/:id
  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit, status: :unprocessable_entity
    end
  end

  # DELETE /posts/:id
  def destroy
    @post.destroy
    redirect_to posts_url, notice: 'Post was successfully deleted.'
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def authorize_post
    unless @post.user == current_user
      redirect_to posts_path, alert: 'Not authorized'
    end
  end

  def post_params
    params.require(:post).permit(:title, :body, :status, tag_ids: [])
  end
end

2. Strong Parameters

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  # Basic strong parameters
  def user_params
    params.require(:user).permit(:name, :email, :password)
  end

  # Nested attributes
  def user_params_with_profile
    params.require(:user).permit(
      :name, :email,
      profile_attributes: [:bio, :avatar, :website]
    )
  end

  # Arrays of permitted attributes
  def post_params
    params.require(:post).permit(
      :title, :body,
      tag_ids: [],
      images: []
    )
  end

  # Conditional parameters
  def user_params
    permitted = [:name, :email]
    permitted << :admin if current_user.admin?
    params.require(:user).permit(*permitted)
  end

  # Deep nested attributes
  def organization_params
    params.require(:organization).permit(
      :name,
      departments_attributes: [
        :id, :name, :_destroy,
        employees_attributes: [:id, :name, :role, :_destroy]
      ]
    )
  end

  # JSON parameters
  def config_params
    params.require(:config).permit(
      settings: [:theme, :notifications, :language],
      preferences: {}
    )
  end
end

3. Filters and Callbacks

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # Before filters
  before_action :authenticate_user!
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :set_time_zone, if: :user_signed_in?

  # After filters
  after_action :log_activity
  after_action :set_cache_headers

  # Around filters
  around_action :measure_action_time

  private

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end

  def set_time_zone
    Time.zone = current_user.time_zone
  end

  def log_activity
    ActivityLogger.log(controller_name, action_name, current_user)
  end

  def set_cache_headers
    response.headers['Cache-Control'] = 'no-cache, no-store'
  end

  def measure_action_time
    start = Time.current
    yield
    duration = Time.current - start
    Rails.logger.info "Action took #{duration}s"
  end
end

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index, :show]
  before_action :set_post, only: [:show, :edit, :update]
  before_action :verify_ownership, only: [:edit, :update]

  prepend_before_action :load_categories
  append_before_action :track_view, only: [:show]

  private

  def verify_ownership
    redirect_to root_path unless @post.user == current_user
  end

  def load_categories
    @categories = Category.all
  end

  def track_view
    @post.increment!(:views_count)
  end
end

4. RESTful Conventions

# config/routes.rb
Rails.application.routes.draw do
  resources :posts do
    # Collection routes (no ID)
    collection do
      get :drafts
      get :search
    end

    # Member routes (with ID)
    member do
      post :publish
      patch :archive
    end

    # Nested resources
    resources :comments, only: [:create, :destroy]
  end

  # Shallow nesting
  resources :authors do
    resources :books, shallow: true
  end

  # Only/except options
  resources :users, only: [:index, :show]
  resources :sessions, except: [:edit, :update]

  # Custom resource names
  resources :posts, path: 'articles'
end

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  # GET /posts/drafts
  def drafts
    @posts = current_user.posts.draft
    render :index
  end

  # GET /posts/search
  def search
    @posts = Post.search(params[:q])
    render :index
  end

  # POST /posts/:id/publish
  def publish
    @post = Post.find(params[:id])
    if @post.publish!
      redirect_to @post, notice: 'Post published'
    else
      redirect_to @post, alert: 'Could not publish post'
    end
  end
end

5. Rendering Responses

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # Renders show.html.erb by default
      format.json { render json: @post }
      format.xml { render xml: @post }
      format.pdf { render pdf: @post }
    end
  end

  def create
    @post = Post.new(post_params)

    if @post.save
      # Redirect to a URL
      redirect_to @post, notice: 'Created'

      # Redirect back with fallback
      redirect_back fallback_location: root_path, notice: 'Created'
    else
      # Render a template with status
      render :new, status: :unprocessable_entity
    end
  end

  def export
    # Render text
    render plain: 'Export complete'

    # Render JSON with status
    render json: { status: 'ok' }, status: :ok

    # Render nothing
    head :no_content

    # Render file
    send_file '/path/to/file.pdf',
      filename: 'document.pdf',
      type: 'application/pdf',
      disposition: 'attachment'

    # Stream file
    send_data generate_csv, filename: 'report.csv',
      type: 'text/csv',
      disposition: 'inline'
  end

  def partial_update
    # Render partial
    render partial: 'post', locals: { post: @post }

    # Render collection
    render partial: 'post', collection: @posts

    # Render with layout
    render 'special_layout', layout: 'admin'

    # Render without layout
    render layout: false
  end
end

6. Error Handling

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :not_found
  rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
  rescue_from ActionController::ParameterMissing, with: :bad_request
  rescue_from Pundit::NotAuthorizedError, with: :forbidden

  private

  def not_found(exception)
    respond_to do |format|
      format.html { render 'errors/404', status: :not_found }
      format.json { render json: { error: exception.message },
                           status: :not_found }
    end
  end

  def unprocessable_entity(exception)
    render json: { errors: exception.record.errors },
           status: :unprocessable_entity
  end

  def bad_request(exception)
    render json: { error: exception.message },
           status: :bad_request
  end

  def forbidden
    respond_to do |format|
      format.html { render 'errors/403', status: :forbidden }
      format.json { render json: { error: 'Forbidden' },
                           status: :forbidden }
    end
  end
end

7. Session and Cookie Management

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def create
    user = User.find_by(email: params[:email])

    if user&.authenticate(params[:password])
      # Set session
      session[:user_id] = user.id

      # Set signed cookie
      cookies.signed[:user_id] = user.id

      # Set encrypted cookie
      cookies.encrypted[:user_token] = user.token

      # Set permanent cookie (20 years)
      cookies.permanent[:remember_token] = user.remember_token

      # Set cookie with options
      cookies[:preference] = {
        value: 'dark_mode',
        expires: 1.year.from_now,
        domain: '.example.com',
        secure: Rails.env.production?,
        httponly: true
      }

      redirect_to root_path
    else
      flash.now[:alert] = 'Invalid credentials'
      render :new
    end
  end

  def destroy
    # Clear session
    session.delete(:user_id)
    reset_session

    # Clear cookies
    cookies.delete(:user_id)
    cookies.delete(:remember_token)

    redirect_to login_path
  end
end

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  private

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def user_signed_in?
    current_user.present?
  end

  helper_method :current_user, :user_signed_in?
end

8. Flash Messages

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def create
    @post = Post.new(post_params)

    if @post.save
      # Standard flash
      flash[:notice] = 'Post created'
      redirect_to @post

      # Flash with redirect
      redirect_to @post, notice: 'Post created'

      # Multiple flash types
      flash[:success] = 'Operation succeeded'
      flash[:error] = 'Something went wrong'
      flash[:warning] = 'Be careful'
      flash[:info] = 'FYI'

      # Flash.now for render (not redirect)
      flash.now[:alert] = 'Validation failed'
      render :new
    end
  end

  def update
    if @post.update(post_params)
      # Flash with custom key
      flash[:custom_message] = 'Custom notification'
      redirect_to @post
    else
      # Keep flash for next request
      flash.keep
      redirect_to edit_post_path(@post)
    end
  end
end

# app/views/layouts/application.html.erb
<%# Display all flash messages %>
<% flash.each do |type, message| %>
  <div class="flash <%= type %>">
    <%= message %>
  </div>
<% end %>

9. API Controllers

# app/controllers/api/v1/base_controller.rb
module Api
  module V1
    class BaseController < ActionController::API
      include ActionController::HttpAuthentication::Token::ControllerMethods

      before_action :authenticate

      rescue_from ActiveRecord::RecordNotFound do |e|
        render json: { error: e.message }, status: :not_found
      end

      private

      def authenticate
        authenticate_or_request_with_http_token do |token, options|
          @current_user = User.find_by(api_token: token)
        end
      end

      def current_user
        @current_user
      end
    end
  end
end

# app/controllers/api/v1/posts_controller.rb
module Api
  module V1
    class PostsController < BaseController
      def index
        @posts = Post.page(params[:page]).per(20)

        render json: @posts,
               meta: pagination_meta(@posts),
               status: :ok
      end

      def show
        @post = Post.find(params[:id])
        render json: @post, status: :ok
      end

      def create
        @post = current_user.posts.build(post_params)

        if @post.save
          render json: @post, status: :created, location: api_v1_post_url(@post)
        else
          render json: { errors: @post.errors },
                 status: :unprocessable_entity
        end
      end

      def update
        @post = current_user.posts.find(params[:id])

        if @post.update(post_params)
          render json: @post, status: :ok
        else
          render json: { errors: @post.errors },
                 status: :unprocessable_entity
        end
      end

      def destroy
        @post = current_user.posts.find(params[:id])
        @post.destroy
        head :no_content
      end

      private

      def post_params
        params.require(:post).permit(:title, :body, :status)
      end

      def pagination_meta(collection)
        {
          current_page: collection.current_page,
          total_pages: collection.total_pages,
          total_count: collection.total_count
        }
      end
    end
  end
end

10. Streaming Responses

# app/controllers/reports_controller.rb
class ReportsController < ApplicationController
  include ActionController::Live

  def export
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] =
      'attachment; filename="report.csv"'

    # Stream CSV data
    User.find_each do |user|
      response.stream.write "#{user.id},#{user.name},#{user.email}\n"
    end
  ensure
    response.stream.close
  end

  def events
    # Server-sent events
    response.headers['Content-Type'] = 'text/event-stream'
    response.headers['Cache-Control'] = 'no-cache'

    10.times do |i|
      response.stream.write "data: #{i}\n\n"
      sleep 1
    end
  ensure
    response.stream.close
  end
end

Best Practices

  1. Follow REST conventions - Use standard CRUD actions when possible
  2. Keep controllers thin - Move business logic to models/services
  3. Use strong parameters - Always sanitize input parameters
  4. Handle errors gracefully - Implement proper error handling
  5. Use before_action - DRY up common operations with filters
  6. Return proper status codes - Use semantic HTTP status codes
  7. Implement proper authentication - Secure your controllers
  8. Use respond_to for multiple formats - Support HTML, JSON, etc.
  9. Leverage flash messages - Provide user feedback
  10. Version your APIs - Use namespacing for API versions

Common Pitfalls

  1. Fat controllers - Putting too much logic in controllers
  2. Missing CSRF protection - Not using authenticity tokens
  3. Weak parameters - Permitting too many or wrong parameters
  4. No error handling - Not rescuing exceptions
  5. Missing authorization - Not checking user permissions
  6. Inconsistent responses - Different status codes for same scenarios
  7. Session bloat - Storing too much data in session
  8. Missing before_action - Duplicating code across actions
  9. Incorrect redirects - Redirecting when rendering is needed
  10. No rate limiting - APIs without throttling

When to Use

  • Building web applications with Rails
  • Creating RESTful APIs
  • Implementing MVC pattern
  • Handling HTTP requests and responses
  • Building admin interfaces
  • Creating CRUD interfaces
  • Implementing authentication flows
  • Building multi-tenant applications
  • Creating webhooks and callbacks
  • Developing content management systems

Resources

平台分布

OpenCode

28.23%
按下载量换算42

Codex

22.91%
按下载量换算34

Claude Code

17.13%
按下载量换算26

windsurf

12.79%
按下载量换算19

Antigravity

7.27%
按下载量换算11

Gemini CLI

3.62%
按下载量换算5

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。

继续浏览同类 Skills