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

Solution 1:

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

Solution 2:

You should use the pluck method as @alony suggested. If you are stuck before Rails 3.2 you can use the ActiveRecord select method together with Array#map:

Post.select(:point).map(&:point)
#=> ["foo", "bar", "baz"] 

before Ruby 1.9 you'd have to do .map{|x| x.title} though, because Symbol#to_proc (aliased by the unary & operator) is not defined in earlier versions of Ruby.

Solution 3:

If you see the definition of select_values , then it using 'map(&:field_name)'

  def select_values(arel, name = nil)
    result = select_rows(to_sql(arel), name)
    result.map { |v| v[0] }
  end

The common and general Rails way to collect all the fields values in array is like :

points = Post.all(:select => 'point').map(&:point)