根据 curl 请求,JSON 在 Rails 上的 Ruby 中输出

JSON output in Ruby on Rails upon curl request

我在 rails 应用程序上构建了一个 Ruby,它使用 HTML 作为默认输出。

现在我要支持JSON。 当我使用带有标志 --header "Accept: application/json" 的命令 curl 时 应返回 JSON 输出。

这里需要哪种实现方式? 使用的方法不得违反 REST 规则。

您需要阅读有关 how to render json 的文档。

基本上,您需要告诉您的控制器方法它能够响应 json :

class UsersController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users}
    end
  end
end