Rails 路由:json 端点命名约定
Rails routes: json endpoint naming convention
我有一个端点呈现 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
成为路线的名称?
有一种更简单的方法来响应不同的格式 - 只需使用 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
我有一个端点呈现 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
成为路线的名称?
有一种更简单的方法来响应不同的格式 - 只需使用 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