Marcelo Alves

find_by vs find_by!

Introduction

user

Marcelo Alves

Web developer living in Central California. Working with Ruby/Rails, Javascript, and dabbling in Elixir. Always searching for solutions that need problems.


notes ruby

find_by vs find_by!

Posted by Marcelo Alves on .
Featured

notes ruby

find_by vs find_by!

Posted by Marcelo Alves on .

.find_by will return a nil when record isn’t found. .find_by! will return ActiveRecord::RecordNotFound.

Recently in a project, .find_by() was being used to find records referenced by a GUID rather than an id. If a record couldn’t be found the server would throw a 500 error. We’d rather have 404 be shown so that’s where .find_by!() comes in.

.find_by! will return an ActiveRecord::RecordNotFound exception with a status code of 404 rendering the 404 template instead of the error template.

user

Marcelo Alves

http://marceloalves.com

Web developer living in Central California. Working with Ruby/Rails, Javascript, and dabbling in Elixir. Always searching for solutions that need problems.