Search code examples
ruby-on-railsdatabaseactiverecordcontrollers

Handling an ActiveRecord error if database is empty


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?


Solution

  • 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