Create a gist now

Instantly share code, notes, and snippets.

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