Can't find a route with an underscore or doesn't treat it properly

落花浮王杯 提交于 2019-12-20 03:50:11

问题


I have this in routes:

Rails.application.routes.draw do
  namespace :api do
    namespace :v3_4 do
      # .....

And the controller app/controllers/api/v3_4/base_controller

module Api
  module V3_4
    class BaseController < ApplicationController
      # ......
    end
  end
end

And app/controllers/api/v3_4/another_controller

module Api
  module V3_4
    class AnotherController < ApplicationController

    end
  end

end

rake routes:

          Prefix Verb        URI Pattern                     Controller#Action
   api_v3_4_test GET         /api/v3_4/test(.:format)        api/v3_4/base#test
 api_v3_4_one GET|OPTIONS /api/v3_4/one(.:format)      api/v3_4/another#one
        api_v3_4 GET|OPTIONS /api/v3_4/two/:id(.:format)  api/v3_4/another#two

And yet for this request I get Routing Error Uninit Constant uninitialized constant Api::V34

Note there's no underscore in the error message. But my project there's no line V34 at all, neither v34, only v3_4 and V3_4


回答1:


Rails inflects _ to be a word separator, so it searches for Api::V34 you can change that behavior by editing config/initializers/inflections.rb:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'V3_4'
end

Moreover, if you want to change Api namespace to API, since it's an acronym, you can do it there as well:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'V3_4'
  inflect.acronym 'API'
end

More info: http://api.rubyonrails.org/classes/ActiveSupport/Inflector/Inflections.html




回答2:


The Ruby-Style-Guide helped me a lot to clarify these questions. Please see the naming section.



来源:https://stackoverflow.com/questions/35981867/cant-find-a-route-with-an-underscore-or-doesnt-treat-it-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!