[英]Creating action API with Rails. Do I need to use respond_with
I am trying to figure out the different ways I can create a create action in a Rails API. 我试图找出在Rails API中创建创建动作的不同方法。 Here's what I have for my index action (which works) and my current implementation of my create action. 这是我的索引操作(有效)和create动作的当前实现的内容。
routes.rb file: route.rb文件:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :vendors
end
end
end
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
require(:suya).permit(:meat, :spicy)
end
end
Do I need to use respond_with/respond_to? 我需要使用respond_with / respond_to吗? That's abstracted out to the responders.gem. 这被抽象到responders.gem中。 If I don't want to use the responders gem is this the best way to create an api? 如果我不想使用响应者gem,这是创建api的最佳方法吗?
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: 是的,因为它是仅负责API调用的API控制器,所以应该使用如下所示的helper方法的respond_to
和respond_with
:
class Api::V1::SuyasController < ApplicationController
respond_to :json
...
def create
respond_with(Suya.create(suyas_params))
end
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.