Skip to content

Instantly share code, notes, and snippets.

@maxivak
Created January 6, 2013 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxivak/5e9ccdfaeded7b4a47af to your computer and use it in GitHub Desktop.
Save maxivak/5e9ccdfaeded7b4a47af to your computer and use it in GitHub Desktop.
Get a list of IDs from database
# 1. connection.select_values or connection.select_all
ids = ActiveRecord::Base.connection.select_values("select id from users WHERE ...")
# array of integers
# ["1", "2", "5", "6", "7", "8", "3", "10", "11", "9"]
# return hashes without model
sql = "sql query"
rows = User.connection.select_all(sql.squish!)
# array of hashes
# 2. If you already have a model:
User.all(:select => :id).collect(&:id)
First approach is faster than the 2nd as it does not incur the cost of constructing model instances.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment