Learn Ruby on Rails Book

find vs find_by vs where in Active Record


Above command will raise and exception if there is not task with id 1.


Using find_by is convenient when we are searching for a record using a column of the record.

1Task.find_by(name: "Get Milk")
2Task.find_by(desc: "Get Eggs")

Note that the bang version(!) of find_by will raise and exception if no record is found.

1Task.find_by!(name: "Get Milk")
2Task.find_by!(desc: "Get Eggs")

Above commands will raise an exception if no record is found.


Active Record allows us to use where to build more complicated queries.

1Task.where(name: "Get Milk", user_id: 3).first

Please not that where operation returns ActiveRecord:Relation. Also note that that return of where clause could be a collection of records.

finder_methods.rb file in Ruby on Rails

Rails has a file named finder_methods which lists a lot of finder methods which are worth taking a look.

There is nothing to commit in this chapter since all we had done was learning the basics of ActiveRecord query methods.