我正在构建一个关于如何为一些学生构建 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/