Pascal Van Hecke
Pascal Van Hecke

Reputation: 4546

How to make Rails parse a posted string as json without sending the 'Content-type: application/json' header?

Rails changes behaviour at several levels when the header 'Content-type: application/json' is sent:

What if I cannot trust the (external) client in passing the right header? In other words, I want to have my application behave as if the client always passes the 'Content-type: application/json' header, even if the client actually does not?

Upvotes: 6

Views: 946

Answers (1)

Adam
Adam

Reputation: 66

You can set the type within an action using

request.format = :json

I tested it using

class ExampleController < ApplicationController

  def always_accept_json
    request.format = :json
    respond_to do |format|
      format.json { raise "HEY" }
      format.html 
    end
  end
end

Which you can do anywhere within Any ActionController i.e. if you wanted at the top level making all request appear to your application as content_type application/json just make it a filter on application_controller.rb that sets request.format

Upvotes: 1

Related Questions