Created
January 6, 2013 05:44
-
-
Save maxivak/4465497 to your computer and use it in GitHub Desktop.
Get a list of IDs from database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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