Rails checking if a record exists in database

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?.


Here is how you can check this.

if Trucks.where(:id => current_truck.id).blank?
  # no truck record for this id
else
  # at least 1 record for this truck
end

where method returns an ActiveRecord::Relation object (acts like an array which contains the results of the where), it can be empty but never be nil.