Rails路由报错求助:已配置路由但仍提示No route matches [GET] "/admin/products"
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
- Save your updated
routes.rband controller files - Restart your Rails server (routing changes sometimes require a restart to take effect)
- Try accessing
/admin/productsagain—this time it should route correctly to yourAdmin::ProductsController#indexaction
内容的提问来源于stack exchange,提问作者Grzegorz Wiktorzak

