Ruby-on-rails 如何将单列的值放入数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9869870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:06:43  来源:igfitidea点击:

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

ruby-on-railsrubyruby-on-rails-3

提问by franklin stine

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?

然后将它们传递给一个方法,我希望我的方法保持不可知,现在必须从我的方法中调用 hash.point。如何快速将其转换为数组并将数据集传递给我的方法,或者有更好的方法吗?

回答by alony

In Rails 3.2 there is a pluck methodfor this

在Rails 3.2有一个拔毛方法对本

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

uniq 和 distinct 之间的区别

回答by Patrick Oscity

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

您应该pluck按照@alony 的建议使用该方法。如果您在 Rails 3.2 之前卡住了,您可以将 ActiveRecordselect方法与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.

在 Ruby 1.9 之前,你必须这样做.map{|x| x.title},因为Symbol#to_proc(由一元运算&符别名)在早期版本的 Ruby 中没有定义。

回答by Vik

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

如果您看到 select_values 的定义,则它使用 '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 :

收集数组中所有字段值的常见和通用 Rails 方法如下:

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

回答by rajibchowdhury

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