nested namespace route going to wrong controller

前端 未结 2 819
无人共我
无人共我 2021-01-24 18:27

Using Rails 3.0.7, I\'m creating an API for our app, and I have this setup:

routes.rb

  namespace :api do
    namespace :v1 do
      match \"connect\" =&         


        
相关标签:
2条回答
  • 2021-01-24 18:58

    skip_before_filter also general takes a symbol parameter for the before filter than you wish to skip. Controller names should not have to be unique as long as the proper scoping/namespacing is applied.

    example

    • api/users_controller
    • admin/users_controller
    • users_controller

    then the code per controller

    class Api::V1::UsersController < Api::V1::BaseController
    end
    
    class Admin:UsersController < Admin::BaseController
    end
    
    class UsersController < ApplicationController
    end
    

    Then the routes

    MyApp::Application.routes.draw do
    
    scope :module => "api" do
      namespace :v1 do
        resources :users
      end
    end
    
    namespace :admin do
      resources :users
    end
    
      resources :users
    end
    
    0 讨论(0)
  • 2021-01-24 18:58

    Rails is a bit confusing, but I had a similar problem. Here's some steps you can take to make sure you're not missing any small code issues. (this eventually led me to discover a syntax bug in the namespaced controller).

    1. run bundle exec rake routes to generate a list of what route links to what controller and action. If this is good, then move to step 2. If not, fix your routes file and try again. (many good tutorials on this, so I won't go into detail)
    2. Go into the rails console, and just load the controller class. If it doesn't work, you may have discovered a bug in syntax. Here's what happened on console when I tried to load the Api::V2::CampaignsController.

      irb> Api::V2::CampaignsController

      => CampaignsController

    Note: Rails is directing all requests to the wrong controller (based on Rails' fancy logic to load controller classes). It should goto Api::V2::CampaignsController, but instead it is loading CampaignsController.

    You can also verify it in the console with:

    > app.get '/api/v2/campaigns.json'
    > app.controller.class
    => CampaignsController
    # This is not the expected controller. 
    

    This ended up being a syntax problem in a class I was extending from the Api::V2::CampaignsController.

    It was a bit mind-boggling, but hope this helps someone else.

    0 讨论(0)
提交回复
热议问题