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

Rails路由报错求助:已配置路由但仍提示No route matches [GET] "/admin/products"

Fixing "No route matches [GET] "/admin/products"" despite route appearing in rake routes

Hey there, let's work through why this routing error is popping up even though you can see the route in rake routes!

The Root Cause

Your current route setup nests the namespace :admin inside a devise_scope + authenticate block—and that's not the right way to define admin routes in Rails.

The devise_scope :user block is designed for overriding or adding custom Devise-specific routes, not wrapping regular namespace routes. When you tuck your admin namespace inside that authenticate block, Rails doesn't properly register the route for general matching. Even though rake routes might display it, the hidden constraints from that block prevent incoming requests from being recognized.

Fixed Route Code

Here's how to adjust your routes.rb to get the admin route working correctly:

Rails.application.routes.draw do 
  root 'static_pages#home'
  resources :products, only: :show
  devise_for :users

  # Move admin namespace outside the devise_scope block
  namespace :admin do
    resources :products
    # Add other admin routes here as needed
  end
end

Securing Admin Routes (The Right Way)

Instead of trying to lock down routes through the devise_scope block, handle authorization directly in your admin controller. You already have authenticate_user!, so just add a check to ensure the user is an admin:

class Admin::ProductsController < ApplicationController
  before_action :authenticate_user!
  before_action :ensure_admin_access!

  def index; end

  private

  def ensure_admin_access!
    unless current_user.admin?
      redirect_to root_path, alert: "You don't have permission to access this page."
    end
  end
end

Optional: Route-Level Constraints (If You Prefer)

If you want to restrict the admin route at the routing layer (so non-admin users get a 404 instead of a redirect), you can use a route constraint:

Rails.application.routes.draw do 
  root 'static_pages#home'
  resources :products, only: :show
  devise_for :users

  namespace :admin do
    resources :products
  end, constraints: lambda { |request| 
    request.env['warden'].authenticate? && request.env['warden'].user.admin? 
  }
end

Final Steps

  1. Save your updated routes.rb and controller files
  2. Restart your Rails server (routing changes sometimes require a restart to take effect)
  3. Try accessing /admin/products again—this time it should route correctly to your Admin::ProductsController#index action

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 02:52:32