【问题标题】:Rails routes: json endpoint naming conventionRails 路由:json 端点命名约定
【发布时间】:2021-12-24 22:20:54
【问题描述】:

我有一个渲染 json 的端点:

def controller_method
   render json: json_response
end

但是,我对路线的命名约定感到好奇。以下命名导致ActionController::UnknownFormat Controller#controller_method is missing a template for this request format and variant.

get '/controller/controller_method.json', to: 'controller#controller_method'

但是,当路由命名时,我成功获取了 json:

get '/controller/controller_method_data', to: 'controller#controller_method'

我不允许在 url 路由中输入.json 吗?有什么方法可以让.json 成为路线的名称?

【问题讨论】:

    标签: ruby-on-rails json routes


    【解决方案1】:

    有一种更简单的方法来响应不同的格式 - 只需使用 ActionController::MimeResponds

    get '/controller/controller_method', to: 'controller#controller_method'
    
    class Controller < ApplicationController
      def controller_method
        respond_to do |format|
          format.json { render json: { hello: 'world' } }
          format.html # renders the view implicitly
          format.txt { render plain: 'Hello world'}
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      相关资源
      最近更新 更多