ruby-on-rails - 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
成为路线的名称?
解决方案
有一种更简单的方法来响应不同的格式 - 只需使用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
推荐阅读
- c# - 调试时直接跳转到Method
- javascript - 使用 javascript 在移动触摸设备上处理带有链接的悬停覆盖图像
- python - 如何更改小部件中按钮的位置(kivy)
- python - 在 Python 中使用 Regex 提取准确的单词或字符集
- node.js - LernaJs tsc 找不到模块
- javascript - 使用 HTML 导入在 DIV 中加载整个 HTML 页面
- php - 有没有一种方法可以让我以常规块大小执行 n 次 ajax 请求?
- python - 如何更改解释器输出形状?
- azure - 将多个 Windows 计划任务从 VM 移植到单个 Web 作业
- javascript - 在 json 数据中写入时,onclick 属性未绑定在 html 代码中