ruby-on-rails - 在 Rails API 中使用 render 而不是 respond_with/to 有什么区别?

标签 ruby-on-rails rails-api

我正在构建一个关于如何为一些学生构建 API 的简单 Rails 教程,并且我在构建它时没有使用 respond_to 和respond_with,因为我只是想看看是否可以在不使用 gem 的情况下构建 api。这就是我所拥有的并且我的测试通过了:

Controller :

class Api::V1::SuyasController < ApplicationController
  def index
    render json: Suya.all
  end

  def create
    render json: Suya.create(suyas_params)
  end


  private

  def suyas_params
    params.require(:suya).permit(:meat, :spicy)
  end
end

路线:
Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :vendors
      resources :suyas
    end
  end
end

测试:
require 'test_helper'

class Api::V1::SuyasControllerTest < ActionController::TestCase
  test "index can get all the suyas" do
    Suya.create(meat: "beef", spicy: true)
    Suya.create(meat: "kidney", spicy: false)

    get :index
    suyas = JSON.parse(response.body)

    assert_equal "beef", suyas[0]["meat"]
    assert_equal true, suyas[0]["spicy"]
    assert_equal "kidney", suyas[1]["meat"]
    assert_equal false, suyas[1]["spicy"]
  end

  test "create can create a suya" do
    assert_difference("Suya.count", 1) do
      create_params = { suya: { meat: "beefy", spicy: true }, format: :json }

      post :create, create_params
      suya = JSON.parse(response.body)

      assert_equal "beefy", suya["meat"]
      assert_equal true, suya["spicy"]
    end
  end
end

使用 render 和 respond_with 有什么区别?我找不到任何答案。甚至有什么我做错了吗?为什么有两种创建 API 的方法(respond_to/respond_with AND this way?)

-杰夫

最佳答案

  • render是 Rails 的一部分 它只是以您所说的任何格式呈现您所说的任何内容。通常是一个 View ,可能是一个字符串,也可能是一个文件。

    一个非常低级的函数,它呈现你所说的一切,根据约定做出一些假设,比如在哪里寻找 View 。
  • respond_to是微DSL 这允许您对请求的不同格式做出不同的响应。

    IE。在与 |format| 的块中调用 format.json需要一个将在请求 JSON 时执行的块,否则将是空操作(无操作)。另外,如果 respond_to没有执行任何块,它以通用的 406 Not Acceptable 响应(服务器不能以客户端可接受的任何格式响应)。

    虽然可以做 if request.json? ,它不是那么可读,需要明确指定何时响应 406。
  • respond_with ,以前是 Rails 的一部分,现在(从 4.2 开始)在 a separate gem responders (对于 reason ),获取一个对象并使用它来构造一个响应(做出很多假设 ,所有这些都可以在 Controller 声明中给出)。

    它使典型用例(即某些 API)中的代码更短。在不太典型的用例中,它可以根据您的需求进行定制。在极不寻常的用例中,它没有用。

  • 我可能过度简化了事情,这是一个总体概述。

    关于ruby-on-rails - 在 Rails API 中使用 render 而不是 respond_with/to 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378177/

    相关文章:

    ruby-on-rails - 在 Heroku/AWS Elastic Beanstalk 上部署 Rails API

    ruby-on-rails - Sidekiq和Twilio闯入 worker “wrong number of arguments (1 for 2)”

    ruby-on-rails - CanCan gem |不能 :index, 用户

    python - 在 Ruby 代码中放置单个断点

    javascript - Angularjs 使用的 Rails API

    active-model-serializers - ActiveModel Serializer JSONAPI 包含的资源

    ruby-on-rails - 如何在已被 Rails 转义的正则表达式中转义\\?

    ruby-on-rails - 每个 Action 分离 rails 日志

    ruby-on-rails - 将 json 文件数据保存到 Rails 数据库中

    ruby-on-rails - 事件模型序列化程序不适用于 rails-api gem