Handling an ActiveRecord error if database is empty

夙愿已清 提交于 2019-12-11 02:55:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!