Brian Lau
Brian Lau

Reputation: 127

controller create method to accept JSON in post route

Basically I have a 'requests_controller' with a create method. I'm supposed to add a POST route that lets the create method accept JSON. I'm kind of confused on how the routing part works. Please help!

We don't need a model or any views. Basically, the controller should accept some JSON like

{url: "http://some-url.com", origin: "some-value-i-will-figure-out-later"}

I have this in my routes.db, but i'm not sure what to put right after the post.

post '' => 'requests#create', :defaults => { :format => 'json' }

Upvotes: 0

Views: 810

Answers (1)

Nimish Gupta
Nimish Gupta

Reputation: 3175

You can try this out

In routes.rb

post '/requests', to: 'requests#create', :defaults => { :format => 'json' }

Your controller logic

class RequestsController < YourBaseClass
  def create
    #your logic - something like give below
    if @object.save
      render json: { success: t(:success_message) }, status: :ok
    else
      render json: { errors: @object.errors.joins(', ') }, status: :unprocessable_entity
  end
end

Hope this helps.

Upvotes: 1

Related Questions