Skip to content

Instantly share code, notes, and snippets.

Created January 6, 2013 05:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save maxivak/4465497 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