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

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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][1] [1]: https://stackoverflow.com/questions/39575398/rails-uniq-vs-distinct

Solution 2 - Ruby on-Rails

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 - Ruby on-Rails

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)

Solution 4 - Ruby on-Rails

points = Post.all.collect {|p| p.point}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfranklin stineView Question on Stackoverflow
Solution 1 - Ruby on-RailsalonyView Answer on Stackoverflow
Solution 2 - Ruby on-RailsPatrick OscityView Answer on Stackoverflow
Solution 3 - Ruby on-RailsVikView Answer on Stackoverflow
Solution 4 - Ruby on-RailsrajibchowdhuryView Answer on Stackoverflow