csduarte
csduarte

Reputation: 191

Prevent the double query?

My goal is to pull data from sql database and split into two arrays (req of library) so that I can graph the data. The problem is that my process is creating two database queries instead of one.

In the controller:

def words_popular
    words = Word.select(:word, :popularity).order(popularity: :desc).limit(100)
    @words = words.pluck(:word)
    @popularity = words.pluck(:popularity)
  end

and the resulting log:

(1.9ms)  SELECT  `dictionary`.`word` FROM `dictionary`  ORDER BY `dictionary`.`popularity` DESC LIMIT 100
(2.0ms)  SELECT  `dictionary`.`popularity` FROM `dictionary`  ORDER BY `dictionary`.`popularity` DESC LIMIT 100

Is the problem the double plucking? Can I do the array split in one line?

Also, in future, is there a way to force the query? In Node mongoose, I would call exec() on the relation to cause it to run.

Upvotes: 1

Views: 144

Answers (2)

alek
alek

Reputation: 331

Try this:

words, popularity = Word.pluck(:word, :popularity).transpose

and than words contains an array of words and popularity an array of popularity.

Upvotes: 1

potashin
potashin

Reputation: 44581

You either use pluck or select. And here you can just use select and map:

words = Word.select(:word, :popularity).order(popularity: :desc).limit(100)
@words, @popularity = words.map(&:word), words.map(&:popularity)

pluck method maps all selected fields in one array while you need separate array for each field.

Upvotes: 1

Related Questions