Active record, how to replace uniq with distinct correctly?

0

I'm trying to retrieve the months I have answers to a search this way:

Answers.pluck('EXTRACT(MONTH FROM created_at)').uniq


(0.7ms)  SELECT EXTRACT(MONTH FROM created_at) FROM 'answers'
=> [3]

This way I have the expected result, but I get a rails warning:

DEPRECATION WARNING: uniq is deprecated and will be removed from Rails 5.1
(use distinct instead) (called from __pry__ at (pry):8)

When I try to follow the suggestion of using distinct without parameters:

Answers.pluck('EXTRACT(MONTH FROM created_at)').distinct()
   (0.4ms)  SELECT EXTRACT(MONTH FROM created_at) FROM 'answers'
NoMethodError: undefined method 'distinct' for [3, 3]:Array
from (pry):33:in '__pry__'

with parameter:

Answers.pluck('EXTRACT(MONTH FROM created_at)').distinct('EXTRACT(MONTH FROM created_at)')
   (0.4ms)  SELECT EXTRACT(MONTH FROM created_at) FROM 'answers'
NoMethodError: undefined method 'distinct' for [3, 3]:Array
from (pry):33:in '__pry__'

Answers.pluck('EXTRACT(MONTH FROM created_at)').distinct(:created_at)
   (0.7ms)  SELECT EXTRACT(MONTH FROM created_at) FROM 'answers'
NoMethodError: undefined method 'distinct' for [3, 3]:Array
from (pry):35:in '__pry__'

Is there another way to use it?

    
asked by anonymous 27.03.2017 / 16:34

1 answer

0

The problem is that when you use pluck it converts to an array and does not pass the object forward. The uniq it is using is a method of the Array class, not ActiveRecord.

It would look like this:

Answer.distinct("mes").select("EXTRACT(MONTH FROM created_at) mes")

It turns out that the result is not so "cool". So we can do a little conversion:

Answer.distinct("mes").select("EXTRACT(MONTH FROM created_at) mes").map{|m| m.mes}

Answer Load (3.2ms)  SELECT DISTINCT EXTRACT(MONTH FROM created_at) mes FROM "answers"
=> [3.0]

If you do not want the result to leave an array of floats just put .to_i at the end of m.mes

    
14.07.2017 / 18:57