
Ruby On Rails Active Record Query methods, find_by() and find() are used to retrieve the record from the database.
.find
.find (by I d) returns a single record or array of objects where multiple arguments are given. There is no implied return order — the sequence is given back in the order found. If one or more of the arguments are not found, the exception is ActiveRecord::RecordNotFound and returns 404. To use this method and prevent this mistake, you can first check for an I d number in your records, but this can be laborious.
Person.find(1) # returns the object for ID = 1
Person.find("1") # returns the object for ID = 1
Person.find("31-sarah") # returns the object for ID = 31
Person.find(1, 2, 6) # returns an array for objects with IDs in
(1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in
(7, 17)
Person.find([1]) # returns an array for the object with ID =1
.find_by(arg, args*)
First, remember the syntactic variations. When searching for an Id in the same way as we illustrated with .find, .find by accepts a key value pair as the parameter by which the data structure can be searched. If the object is found, it will be returned. If this is not the case, a nil value will be returned and the program will continue to run without exception. Finds and returns the first match.
Post.find_by(name: 'Spartacus', rating: 4)
Post.find_by(id: params[:id])
In the interview, this question may be asked, by the interviewer.
What is the difference between find() and find_by()?
The difference is when they’re going to return whenever a record is not found.
find_by() returns nil while find() returns ActiveRecord::RecordNotFound exception.
The additional difference between find() and find_by() is that find could only be used to search by primary key (usually the ‘id’) while the find_by() requires and searches by attribute (either passed as hash like Employee.find_by(name: ‘Mike’) or using the Employee.find_by_name(‘Mike’) method).
Thanks For Reading
[…] find & find_by […]