Search code examples
ruby-on-railshttp-status-codesrespond-with

Using respond_with to serve 404?


I'm trying to serve up a custom 404 response in rails, but I'm not sure how to give the :status to a respond_with function.

I know with render, I can do something like this:

render :status => :not_found, :json => {:response =>"There weren't any results"}

How can I do something like that with respond_with? Is there even a way to set status codes with respond_with?

The only reason I'm using respond_with is because, to my understanding, it is proper protocol to use respond_with when you've started with respond_to. If that isn't correct and I should be using render, please let me know!


Solution

  • See the docs; respond_with takes :status as an option.

    respond_with(@user, status: :not_found) do |format|
      format.json { response: "There weren't any results" }
    end