我正在構建一個關於如何爲一些學生構建API的簡單的rails教程,並且我正在構建它而沒有respond_to和respond_with,因爲我只想看看是否可以在不使用gem的情況下構建api。這是我和我的測試都通過了:在Rails API中使用render而不是respond_with/to有什麼區別?
控制器:
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
什麼是使用渲染VS respond_with之間的區別?我找不到任何答案。有什麼我做錯了嗎?爲什麼有兩種方法來創建的API(respond_to代碼/ respond_with而這樣一來?)
-Jeff
你面臨什麼問題? – Ojash
從你的角度來看代碼有什麼問題?你得到什麼錯誤? – Makoto
基本上,爲什麼有兩種方法可以做到這一點?我的方式和另一種方式有什麼區別?我的測試通過和一切......我只是不知道這兩種方式存在。 – Jwan622