Find

This method will find a single record or array of records from the table based on the arguments by comparing with primary key of the table (defaults to id) and returns it.If a record is not found, it will raise an ActiveRecord::RecordNotFound exception.

# record found
User.find(5)          => #<User id: 5, name: "Test">
User.find(1, 5)      => [#<User id: 1, name: "Bob">, #<User id: 4, name: "Test">]

# record not found
User.find(5)          => ActiveRecord::RecordNotFound (Couldn't find User with 'id'=5)
User.find(1, 5)      => ActiveRecord::RecordNotFound (Couldn't find all Users with 'id': (1, 5) 
          (found 1 results, but was looking for 2)

Find_by

This is similar to find but this can find a record based on any column not only primary key (ID) of the table and returns the first record that matches a given condition. If a record is not found, nil is returned

# record found
User.find_by(name: “Bob”, location: “India”)   => #

# record not found
User.find_by(name: “Bob”, location: “India”)   => nil

Where

where returns an ActiveRecord::Relation, which is a collection of model objects.If nothing matches the conditions, it simply returns an empty relation.

# record found
User.where(name: “Bob”, location: “India”)
=> #,
                                               #]...>
# record not found
User.where(name: “Bob”, location: “India”)   => #

– Use whichever one you feel suits your needs best.

Support On Demand!

Ruby on Rails