'Resource not found errors in Ruby on rails
I know that ActiveRecord::RecordNotFound
can be mapped to http 404 error. Is there any other resource in ruby on rails whose non-existence will raise something like
ResourceName::ResourceNameNotFound
?
Also are there any errors raised by RoR which are equivalent to 520, 403, 401 ?
Solution 1:[1]
Rails should respond with the proper HTTP error codes in correlation to the conventions of the HTTP protocol. I've worked with Rails for a while and haven't seen any exceptions. You can also raise your own exceptions like this
@record = ModelName.find_by(field_name_goes_here: params[:some_parameter_name_goes_here])
if not @record.blank?
render "view_file_name_goes_here"
else
raise ActiveRecord::RecordNotFound
end
This code will cause rails to respond with a 404. Making a request for a route that has not been defined will also result in a 404.
Other examples:
A syntax error in your code will respond with a 500.
If you are using devise or some other gem for authorization, an unauthorized request will result in rendering a 401. There won't be anything in Rails that would render a 401 out of the box. Remember, all of your requests are defined through routes.rb and it's up to your controllers to decide what response to render and if that response should return an HTTP error code.
This question here provides information on how to render all types of error codes:
Return a specific http status code in Rails
If you are looking to debug the http error code I would suggest setting the rails environment configuration to consider all requests as local requests. This will display an understandable error.
Purpose of "consider_all_requests_local" in config/environments/development.rb?
Solution 2:[2]
In rails you can raise error when your particular result is mismatch
like you mention ActiveRecord::RecordNotFound
and each error has its meaning like.
401 is for NOT_AUTHORIZED
403 is for FORBIDDEN
500 is for server error
and there are many other
Solution 3:[3]
Missing
def index
end
will do,
if not, restart your computer and everything is fine
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ankur Pohekar |
Solution 3 |