In the previous chapter we learnt how we can query a task from the database
There are several methods which we can use to query one or more than one records from database. In this chapter we will take a look at these finder methods.
Let's take an example where a task with ID 1 doesn't exist. What happens when we query a task record with ID 1. Before moving on, pause for a moment to think about what will be the output if we query a record which doesn't exist. Will we get a null value for output?
To answer the question, it depends upon the finder_method used to query data.
For eg, If we use the
The above command will raise an exception if there doesn't exist a task with ID 1. You can get away with it if you properly handle exceptions in your Rails application. Handling exceptions is always a good thing.
But how do we prevent exceptions? Let's take a look at some other finder_methods to answer that question.
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")
If a record isn't found then the
find_by method will return a
Note that the bang version(!) of
find_by will raise an exception if no record
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 complex queries:
1Task.where(name: "Get Milk", user_id: 3).first
Please note that
where operation returns
ActiveRecord:Relation. Also note
that return of where clause could be a collection of records.
finder methods 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.