24

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

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

4 Answers 4

76

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This gives me [141, 138, 123, 128, 137, 139]
I need the "" around the numbers like this: ["141", "138", "123", "128", "137", "139"]
Try replacing collect(&:id) with collect{|u|u.id.to_s}
16

If you have a has_many, then on the has_many side you can get the IDs for associated objects like this:

def User
  has_many :tasks
end

def Task
  belongs_to :user
end

ids = User.find(1).task_ids

Comments

6

How about:

ClassName.all.collect { |obj| obj.id }

4 Comments

This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.
No, this was an answer, and is very similar to the accepted answer. I don't know what gives you the impression that this is a comment.
It should be: ClassName.pluck(:id) or ClassName.all.collect(&:id)
I agree @Justin. Looking back years later, my answer was a n00b response and probably doesn't deserve the 3 votes it has :)
3

If you use Model, there are new method - pluck. Comment.pluck(:id) #[1,2,3...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.