【问题标题】:Routing Error uninitialized constant rails路由错误未初始化的常量轨道
【发布时间】:2016-08-09 10:56:03
【问题描述】:

我收到此错误。当我想在 localhost:3000/api/v1/songs.json 上运行 te 服务器时 路由错误 未初始化的常量 API::V1::SongsController。 那是我的 routes.rb 文件:

Rails.application.routes.draw do
    namespace :api do 
        namespace :v1 do 
            resources :songs, only: [:index, :create, :update, :destroy]
        end
    end  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

路线

路由从上到下优先匹配

Helper  HTTP Verb   Path    Controller#Action
Path / Url      
Path Match
api_v1_songs_path   GET /api/v1/songs(.:format) 
api/v1/songs#index

POST    /api/v1/songs(.:format) 
api/v1/songs#create

api_v1_song_path    PATCH   /api/v1/songs/:id(.:format) 
api/v1/songs#update

PUT /api/v1/songs/:id(.:format) 
api/v1/songs#update

DELETE  /api/v1/songs/:id(.:format) 
api/v1/songs#destroy

这就是我的 SongsController:

class Api::V1::SongsController < Api::V1::BaseController
  def index
    respond_with Song.all
  end

  def create
    respond_with :api, :v1, Song.create(song_params)
  end

  def destroy
    respond_with Song.destroy(params[:id])
  end

  def update
    song = Song.find(params["id"])
    song.update_attributes(song_params)
    respond_with song, json: song
  end

  private

  def song_params
    params.require(:song).permit(:id, :name, :singer_name, :genre, :updated_at, :tag)
  end
end

【问题讨论】:

  • 您可能没有正确地为 SongsController 命名空间,正如错误消息中所说的那样。
  • 我可以知道你的控制器目录结构吗,因为我认为它必须在 app/controllers/api/v1/songs_controller.rb 中
  • 我上面有这样的 SongsController
  • 把你的namespace :v1改成namespace :V1
  • 现在我收到此错误;

标签: ruby-on-rails


【解决方案1】:

我将复制我们的运行方式,因为我看不出您的代码和我们的代码之间的直接区别......

routes.rb

constraints subdomain: Settings.subdomains.api do  # you can ignore this
  namespace :api do
    namespace :v1 do
      resources :maps, only: [] do
        collection do
          get :world_map
        end
     end
   end
 end

ma​​ps_controller.rb

module Api
  module V1
    class MapsController < BaseController
      def world_map; end
    end
  end
end

路由输出

world_map_api_v1_maps GET     /v1/maps/world_map(.:format)  api/v1/maps#world_map {:subdomain=>"api"}

就我所见,拼写真的很重要。 我们的directort结构:

app/controllers/api/v1/maps_controller.rb

所以检查这些点,这应该可以工作,因为它是标准的 Rails 魔法。

【讨论】:

  • 不幸的是它不能正常工作我不明白我的问题是什么?
  • 最后的猜测,按照我的方式编写控制器,定义模块,而不是内联......
猜你喜欢
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 2014-02-01
  • 2015-05-23
相关资源
最近更新 更多