我有一個渲染 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'
我不允許放入.jsonurl 路由嗎?我可以允許的任何方式是.json路線的名稱?
uj5u.com熱心網友回復:
有一種更簡單的方法來回應不同的格式 - 只需使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358376.html
上一篇:JSON.parse(message)失敗,但“https://jsonlint.com/”顯示訊息有效。為什么會發生這種情況?
