0

I have a query that returns a 2d array, but would like it to return a 1d array of results. Given:

sql = "SELECT `id` FROM things WHERE other_id = 8"
ids = ActiveRecord::Base.connection.execute(sql).to_a

ids is then equal to

[[1],[2],[3],[4],[5],[9]....]

I was using map to create a new array, but it was terribly slow with more than 5000 records. What is the fastest method of obtaining the following format:

[1,2,3,4,5,9...]

1
  • Why do you need an array, is it really necessary? Because if you only need a collection of ids to iterate on, or build a subquery, there are far better ways of doing this. Just trying to help, even if that's a bit beyond the scope of the question. Commented Nov 6, 2014 at 16:33

3 Answers 3

5

You can do as

sql = "SELECT `id` FROM things WHERE other_id = 8"
ids = ActiveRecord::Base.connection.execute(sql).to_a.flatten

More Rails way is to use #pluck as below :-

Thing.where(other_id: 8).pluck(:id)
Sign up to request clarification or add additional context in comments.

3 Comments

@japed Hehehe.. Chill :-)
Yeah, pluck is the way to go here.
I'm not so sure he actually has a model defined, but we'll find that out shortly ._. If that's the case, you might want to add some references on how to generate and deal with a Rails model.
2

Why do you use the execute statement? Use an ActiveRecord model.

Thing.where(other_id: 8).pluck(:id)
# => [1, 2, 3, 4]

Comments

1

Assuming your models and associations are set up correctly, i.e.

class Thing < ActiveRecord::Base
  belongs_to :other
end

class Other < ActiveRecord::Base
  has_many :things
end

you can use ids:

Thing.where(other_id: 8).ids  #=> [1, 2, 3, 4, 5, 9 ...]

or, coming from Other:

Other.find(8).things.ids      #=> [1, 2, 3, 4, 5, 9 ...]

or:

Other.find(8).thing_ids       #=> [1, 2, 3, 4, 5, 9 ...]

1 Comment

thing_ids is the cute one.. :D

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.