Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails checking if a record exists in database

What is the most efficient of way of checking if a database will return a record before processing it. Example: Truck.where("id = ?", id).select('truck_no').first.truck_no

This may or may not return a truck if the truck exists. What is the most efficient way for me to ensure the page will not crash when processing this request. How would I handle this both in the view and the controller if lets say I was using a loop to go through each truck and print out its number.

If the record does not exist I would like to be able to print out a message instead saying no records found.

like image 614
Bagzli Avatar asked Aug 06 '13 14:08

Bagzli


People also ask

How do you destroy in rails?

Rails delete operation using destroy methodBy using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.


1 Answers

If you want to check for the existence of an object why not use exists?

if Truck.exists?(10)   # your truck exists in the database else   # the truck doesn't exist end 

The exists? method has the advantage that is not selecting the record from the database (meaning is faster than selecting the record). The query looks like:

SELECT 1 FROM trucks where trucks.id = 10 

You can find more examples in the Rails documentation for #exists?.

like image 86
cristian Avatar answered Sep 22 '22 10:09

cristian