使用 Rails 创建动作 API.我需要使用 response_with [英] Creating action API with Rails. Do I need to use respond_with
问题描述
我正在尝试找出在 Rails API 中创建创建操作的不同方式.这是我的索引操作(有效)和我的创建操作的当前实现.
I am trying to figure out the different ways I can create a create action in a Rails API. Here's what I have for my index action (which works) and my current implementation of my create action.
routes.rb 文件:
routes.rb file:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :vendors
end
end
end
控制器:
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
require(:suya).permit(:meat, :spicy)
end
end
我需要使用respond_with/respond_to吗?这被抽象到responders.gem.如果我不想使用响应者 gem,这是创建 api 的最佳方式吗?
Do I need to use respond_with/respond_to? That's abstracted out to the responders.gem. If I don't want to use the responders gem is this the best way to create an api?
推荐答案
因为它是 API 控制器,只负责 API 调用,是的,你应该使用 respond_to
和 respond_with
辅助方法如下所示:
As it's API controller which is responsible for only API calls, yes, you should use respond_to
and respond_with
helper methods as shown below:
class Api::V1::SuyasController < ApplicationController
respond_to :json
...
def create
respond_with(Suya.create(suyas_params))
end
...
end
这篇关于使用 Rails 创建动作 API.我需要使用 response_with的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!