[ruby-on-rails] 단일 열의 값을 배열로 가져 오는 방법

지금은 단일 데이터 열을 선택하기 위해 다음과 같은 작업을 수행하고 있습니다.

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

그런 다음 메서드에 전달하면 메서드가 독립적으로 유지되기를 원하며 이제 메서드 내에서 hash.point를 호출해야합니다. 이것을 배열로 신속하게 변환하고 데이터 세트를 내 메소드로 전달하는 방법 또는 더 나은 방법이 있습니까?



답변

Rails 3.2에는이를위한 pluck 메소드 가 있습니다.

다음과 같이 :

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)

유니크와 구별의 차이점


답변

pluck@alony가 제안한 방법을 사용해야합니다 . Rails 3.2 이전에 멈춘 경우 ActiveRecord select메서드를 다음과 함께 사용할 수 있습니다 Array#map.

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

.map{|x| x.title}하지만 Ruby 1.9 이전 Symbol#to_proc에는 (단항 &연산자로 별칭이 지정됨 ) 이전 버전의 Ruby에서 정의되지 않았기 때문에 해야 합니다.


답변

select_values의 정의가 보이면 ‘map (& : field_name)’을 사용합니다.

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

배열의 모든 필드 값을 수집하는 일반적인 Rails 방법은 다음과 같습니다.

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


답변

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


답변