问题
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?
回答1:
One method you can use is the exists?
active record method, like so:
@issue = Issue.where(id: 1)
if @issue.exists?
# do something if it exists
else
# do something if it is missing
end
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 APIDoc
回答2:
In 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 found
@issue = Issue.find_by(id: 1)
回答3:
you can handle that exception in your controller
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def record_not_found
flash[:alert] = "invalid information"
redirect_to root_url
end
or you can use a where clause
@issue = Issue.where(id: 1).first
now check for nil by
@issue.nil?
来源:https://stackoverflow.com/questions/20909385/handling-an-activerecord-error-if-database-is-empty