Ahkshay Ravi
Ahkshay Ravi

Reputation: 49

How to Convert ActiveRecord_Relation to an normal array in rails

I have an model which returns an active record relation. How to convert this active record relation into an normal ruby array?

Upvotes: 0

Views: 4720

Answers (2)

guitarman
guitarman

Reputation: 3320

If you need an array of one or more model attributes for your relation, then you can just use ActiveRecord::Calculations#pluck.

From the docs:

Person.pluck(:id)
# SELECT people.id FROM people
# => [1, 2, 3]

Person.pluck(:id, :name)
# SELECT people.id, people.name FROM people
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

And there's more what you can do.

Upvotes: 5

Vasfed
Vasfed

Reputation: 18504

Relation has to_a method, which does exactly that. It is used internally for methods like any?

Upvotes: 4

Related Questions