How to send http-status using JBuilder Gem

2019-04-07 03:04发布

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

4条回答
狗以群分
2楼-- · 2019-04-07 03:37

maybe reverse the thinking:

@pictures = ...
respond_to do |format|
  format.html
  format.json do 
    if @error.present? # @error contains some error message
      render json: @error, status: :unprocessable_entity
    else
      render template: 'api/shared/index.jbuilder'
    end
  end

api/shared/index.jbuilder

json.array! @pictures, :id, :filename, :width, :height

works in Rails5.1.4

查看更多
相关推荐>>
3楼-- · 2019-04-07 03:39

This works:

controller

def some_action
  render status: :bad_request
end

some_action.jbuilder

json.something "test"
查看更多
ら.Afraid
4楼-- · 2019-04-07 03:55

I don't know about Rails 3.0, but I was able to provide the appropriate status by simply adding a respond_to block to the controller action. As an example, I have an create like so:

def create
  # ... create logic

  respond_to do |format|
    format.html
    format.json {
      render status: :created, success: true
    }
end

The above code sets my status code to 201 and renders app/views/orders/create.json.jbuilder

Hope that helps.

查看更多
时光不老,我们不散
5楼-- · 2019-04-07 04:01

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 }
查看更多
登录 后发表回答