Active record, how to replace Uniq with distinct correctly?

Asked

Viewed 89 times

0

I’m trying to recover the months where I have answers to a survey 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 Warning from Rails:

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 to use 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__'

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__'

The way to use it is another?

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 and not Activerecord.

It would be right:

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

Turns out the result doesn’t look 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 exit an array of floats just put .to_i at the end of the month.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.