Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a single column's values into an array

Right now I'm doing something like this to select a single column of data:

points = Post.find_by_sql("select point from posts") 

Then passing them to a method, I'd like my method to remain agnostic, and now have to call hash.point from within my method. How can I quickly convert this into an array and pass the data set to my method, or is there a better way?

like image 697
franklin stine Avatar asked Mar 26 '12 09:03

franklin stine


1 Answers

In Rails 3.2 there is a pluck method for this

Just like this:

Person.pluck(:id) # SELECT people.id FROM people Person.pluck(:role).uniq # unique roles from array of people Person.distinct.pluck(:role) # SELECT DISTINCT role FROM people SQL Person.where(:confirmed => true).limit(5).pluck(:id) 

Difference between uniq and distinct

like image 55
alony Avatar answered Sep 28 '22 17:09

alony