Reputation: 191
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
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
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