Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array of IDs

Tags:

Hi How can I return an array from a database call.

in this format: ["141", "138", "123", "128", "137", "139"]

like image 630
andkjaer Avatar asked Nov 11 '10 16:11

andkjaer


1 Answers

In Rails 4: (ht @ri4a)

User.ids # integer array User.ids.map(&:to_s) # string array 

In Rails 3/4:

User.pluck(:id) # integer array User.pluck(:id).map(&:to_s) # string array 

Old answer

If you want to go directly to the DB:

> ActiveRecord::Base.connection.select_values("select id from users") ["1", "2", "5", "6", "7", "8", "3", "10", "11", "9"] 

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.

like image 195
Harish Shetty Avatar answered Oct 16 '22 04:10

Harish Shetty