3

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!

RileyE
  • 10,874
  • 13
  • 63
  • 106

2 Answers2

7

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
deefour
  • 34,974
  • 7
  • 97
  • 90
  • Sorry. I'm not sure how I missed your answer. Thank you so much! That's perfect. Unfortunately, I'm new to ruby and I was looking for `respond_with` in the docs and not `Responder`. This is exactly what I need. – RileyE Mar 06 '13 at 15:38
2

Instead of set a specific 404 status in your response, you could just raise a ActiveRecord::RecordNotFound exception and it has the same effect. Check it here

Community
  • 1
  • 1
Alter Lagos
  • 12,090
  • 1
  • 70
  • 92
  • Sorry for any confusion, but with `ActiveRecord::RecordNotFound` will not allow for custom responses. I know that wasn't very clear in my question, but I do appreciate the response as its helpful to know. Thank you! – RileyE Mar 06 '13 at 15:40
  • 1
    The problem with raising `ActiveRecord::RecordNotFound` is that it will be logged as an exception and depending on your API it isn't an exception. Maybe you only want to check if a resource exists. For e.g. if the cart doesn't exist (not_found), create it, basically try a get to show, if it returns not_found, make a post to create. – Pablo Cantero Jun 07 '13 at 20:39