Jwan622
Jwan622

Reputation: 11659

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. Here's what I have for my index action (which works) and my current implementation of my create action.

routes.rb file:

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? 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?

Upvotes: 1

Views: 182

Answers (1)

RAJ
RAJ

Reputation: 9747

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

Upvotes: 1

Related Questions