Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send http-status using JBuilder Gem

Am using Rails 3.0.19 and JBuilder Gem 2.0.6 to render JSON responses.

JBuilder: https://github.com/rails/jbuilder

Following is the code am using to send error-messages for a specific API.

render :json, :template=>"/api/shared/errors.json.jbuilder", :status=> :bad_request 

For some reason, the client receives 200-ok status. While, I have expected 400 (bad_request).

Any help, please?

Here is my code in detail:

  def render_json_error_messages
    #render :template=> "/api/shared/errors.json.jbuilder", :status=> :bad_request, :formats => [:json]
    respond_to do |format|
      format.json {
        render :template=> "/api/shared/errors.json.jbuilder", :status=> 400
      }
    end
  end

And in a before_filter method, I use render_json_error_messages

like image 743
Satya Kalluri Avatar asked Jul 07 '14 13:07

Satya Kalluri


2 Answers

This works:

controller

def some_action
  render status: :bad_request
end

some_action.jbuilder

json.something "test"
like image 134
ndreckshage Avatar answered Oct 21 '22 21:10

ndreckshage


Try rendering jbuilder to string then set the status... works in Rails 4.1.4

jstr = render_to_string( template: 'api/shared/index.jbuilder', locals: { nodes: @nodes})
respond_to do |format|
  format.html
  format.json { render json: jstr, status: :bad_request }
end

Else following also works

format.json { render template: 'api/shared/index.jbuilder', status: 404 }
like image 39
girishso Avatar answered Oct 21 '22 22:10

girishso