Skip to content

Instantly share code, notes, and snippets.

@mirrec
Last active August 29, 2015 13:56
Show Gist options
  • Save mirrec/8958537 to your computer and use it in GitHub Desktop.
Save mirrec/8958537 to your computer and use it in GitHub Desktop.
This is a should guide of knowledge, where I demonstrate some issues and offer solution for them.

any record exists

bad

  @any_user = User.all.any?        # SELECT `users`.* FROM `users`
  @any_user = User.scoped.present? # SELECT COUNT(*) FROM `users`
  • fetch all data from database
  • load memory for all needed objects

good

@any_user = User.exists? # SELECT 1 AS one FROM `users` LIMIT 1
  • efective
  • quick
  • readble

sorting LIFO

bad

  User.order("created_at DESC")
  • you need additional index for timestamp column
  • if two record where added at the same second, result will not be correct

good

  User.order("id DESC")
  • using primary key
  • correct result if two record where added at the same second
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment