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

Jwa*_*622 9 ruby-on-rails rails-api

我正在构建一个关于如何为一些学生构建API的简单rails指南,我正在构建它而没有respond_to和respond_with,因为我只是想看看我是否可以在不使用gem的情况下构建api.这就是我所拥有的和我的测试通过:

控制器:

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
Run Code Online (Sandbox Code Playgroud)

路线:

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :vendors
      resources :suyas
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

测试:

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
Run Code Online (Sandbox Code Playgroud)

使用render和respond_with有什么区别?我找不到任何答案.有没有我做错的事情?为什么有两种方法来创建API(respond_to/respond_with AND这种方式?)

-Jeff

D-s*_*ide 16

  • render是Rails的一部分,它只是以你说的任何格式呈现你所说的任何内容.通常是视图,可能是字符串,可能是文件.

    一个非常低级的函数,它可以呈现您所说的每个约定做出一些假设,例如在哪里查找视图.

  • respond_to是一种微型DSL,允许您以不同的方式响应所请求的不同格式.

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

    尽管可以这样做if request.json?,但它不是那么可读,需要明确指定何时响应406.

  • respond_with以前是Rails的一部分,现在(自4.2起)在一个单独的gem中responders(出于某种原因),接受一个对象并使用它来构造一个响应(做出很多假设,所有这些都可以在控制器声明中给出).

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

我可能过度简化了事情,这是一个概括性的概述.