How to send http-status using JBuilder Gem

人走茶凉 提交于 2019-12-04 04:01:46

This works:

controller

def some_action
  render status: :bad_request
end

some_action.jbuilder

json.something "test"

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 }

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!