I'm working on a rails 4 app, and i have the following controller code
def index
@issue = Issue.find(1)
@sections = @issue.sections
@articles = @issue.articles
end
which breaks if the database is empty with the error: "Couldn't find Issue with id=1". What is the proper way to check for this in a way that if nothing is in the db it doesn't raise an error?
One method you can use is the
exists?
active record method, like so:Side note: Since you're attempting to find by
id
, you don't necessarily need the.where
portion; you can simply do:Issue.exists?(1)
.exists?
documentation on APIDocIn most cases such exception is expected and recommenced. For example, you can rescue it with a custom 404 page.
Anyway, if you really don't want that, you can use
find_by
method which will output nil if nothing foundyou can handle that exception in your controller
or you can use a where clause
now check for nil by