首页 > 解决方案 > Rails 路由:json 端点命名约定

问题描述

我有一个呈现 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'

我不允许.json输入 url 路由吗?我可以允许任何方式.json成为路线的名称?

标签: ruby-on-railsjsonroutes

解决方案


有一种更简单的方法来响应不同的格式 - 只需使用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

推荐阅读