在 Rails 中,我的 RESTful 路由抛出 404,即使我已经在 config/routes.rb 中配置了路由

In Rails my RESTful route is throwing a 404 even though I have configrued the route in config/routes.rb

我正在使用 Rails 4.2.3。我有一个只有一种方法的控制器

class CountriesController < ApplicationController

   def states
      @country = Country.find params[:country_id]
      @states = @country.states
      respond_to do |format|
         format.json { render json: @states.to_json }
      end
   end

end

在我的 config/routes.rb 文件中我设置了

resources :countries do
    get :state, on: :member #-> url.com/countries/:country_id/states/
end

但是,当我访问 URL

http://mydomein.devbox.com:3000/countries/38/states

我得到了 404。我还需要做什么才能让它工作?

编辑: 我编辑了我的 coffeescript 以匹配建议(添加内容类型),但这仍然导致 404 ...

@update_states = (countryElt, stateElt) ->
   url = "/countries/" + $(countryElt).val() + "/states"
   $.ajax
     url: url
     type: 'GET'
     contentType: 'application/json'
     success: (data) ->
       for key, value of data
         $(stateElt).find('option').remove().end()
         $(stateElt).append('<option value=' + key + '>' + value + '</option>')

您的服务器找不到路由,因为控制器and/or请求没有正确写入。

首先,在rails中触及config/routes.rb时,需要重启服务器(基本上所有config文件夹中的修改文件都可以应用此规则)。

编辑

其次,你的resources函数不正确,试试这个:

resources :countries do
     get :states # >> url.com/countries/:country_id/states
end

根据您当前的配置,您的服务器正在寻找 countries#state 操作,尽管您的 controller/action 名为 countries#states

编辑结束

其次,您的请求和您的控制器不匹配。您正在编写 HTML 响应的请求,但您的控制器仅响应 json。尝试在请求中设置一个'Content-Type': 'application/json' header,或者直接在请求中写格式:http://your-url.com/countries/38/states.json.

如果您还需要在 HTML 中进行响应,则需要将此格式添加到控制器方法中:

class CountriesController < ApplicationController

  def states
    @country = Country.find params[:country_id]
    @states = @country.states
    respond_to do |format|
      format.html # if your views were generated you may not need to specify a template or its variables
      format.json { render json: @states.to_json }
    end
  end
end

有了这两条路线(html 和 json)将由您的服务器找到。您原来的 url 应该可以使用它!