【问题标题】:In Rails my RESTful route is throwing a 404 even though I have configrued the route in config/routes.rb在 Rails 中,即使我在 config/routes.rb 中配置了路由,我的 RESTful 路由也会抛出 404
【发布时间】:2016-06-27 21:20:48
【问题描述】:

我使用的是 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。我还需要做什么才能让它工作?

编辑:我编辑了我的咖啡脚本以匹配建议(添加内容类型),但这仍然导致 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>')

【问题讨论】:

    标签: ruby-on-rails-4 routes config restful-url


    【解决方案1】:

    您的服务器找不到路由,因为控制器和/或请求未正确写入。

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

    编辑

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

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

    使用您当前的配置,您的服务器正在寻找 countries#state 操作,尽管您的控制器/操作被命名为 countries#states

    编辑结束

    其次,你的请求和你的控制器不匹配。您正在编写 HTML 响应请求,但您的控制器仅响应 json。尝试在请求中设置'Content-Type': 'application/json' 标头,或者直接在请求中写入格式: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)。您的原始网址应该可以使用!

    【讨论】:

    • 因为我正在处理 jQuery ajax 调用,所以我只想专注于 JSON 路由。我在我的问题中包含了我的 ajax 调用,以证明我已经添加了“contentType”标头。但是,我仍然得到 404。此外,我什至将 URL 更改为“states.json”,但也得到了 404。
    • 刚刚更新了我的答案,如果您遇到类似问题,请检查并评论
    猜你喜欢
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多