You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails如何在route.rb中配置路由指向admin子目录下的控制器动作

路由指向Admin控制器的配置方法

要让hoge/feeds/api_index路径映射到Admin::FeedsController,有两种规范配置方案:

方案1:显式指定控制器

# routes.rb
Rails.application.routes.draw do
  scope '/hoge' do
    # 需要复数路径用resources写法更规范,不需要多余前缀直接指定controller参数即可
    resources :feeds, controller: 'admin/feeds', only: [] do
      collection do
        get :api_index
      end
    end
  end
end

方案2:使用命名空间块配置

# routes.rb
Rails.application.routes.draw do
  scope '/hoge' do
    # path设为空可以避免路由自动生成/admin前缀,完全匹配你需要的路径规则
    namespace :admin, path: '' do
      resources :feeds, only: [] do
        collection do
          get :api_index
        end
      end
    end
  end
end

配置完成后执行rails routes命令校验,确认api_index对应的Controller列为admin/feeds即可。


修改配置后方法未定义报错的解决方法

undefined local variable or method 'api_index' for Admin::FeedsController:Class报错和路由配置无关,属于控制器代码语法问题,优先排查以下两点:

  • 检查app/controllers/admin/feeds_controller.rb的语法完整性:你贴出的代码片段只写了def api_index,没有方法结束的end,也没有类闭合的end,会导致方法没有被正确定义在类作用域内
  • 确认控制器类名、文件名拼写完全匹配:文件名必须是feeds_controller.rb,类名必须是class Admin::FeedsController < ApplicationController,大小写、命名空间不能出错

修正语法问题后重启Rails服务即可解决报错。

内容的提问来源于stack exchange,提问作者Hinoarashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:18:03