Omar
Omar

Reputation: 243

How can I convert a single column of an array of Active Record objects into an array of strings?

I have an array of rails ActiveRecord objects, and I need to extract a single string column into an array. Is there an easy way to get ActiveRecord to return my simple array without writing a loop?

Currently I have:

myObjects = MyObject.all
myArray = []
myObjects.each do |obj|
  myArray << obj.field_name
end

I'd like to have something like:

myArray = MyObject.all.give_me_the_array_of(:field_name)

Upvotes: 0

Views: 1014

Answers (2)

j-dexx
j-dexx

Reputation: 10416

You can use pluck

MyObject.pluck(:field_name)

Upvotes: 3

Saurabh
Saurabh

Reputation: 73659

Following one liner should work:

myArray = MyObject.all.map{|a| a.field_name}

Upvotes: 0

Related Questions