简体   繁体   中英

Rails 6 select random ActiveRecord object for each category

I've got TestQuestion model where I store survey questions with predefined and hardcoded categories:

CATEGORIES = %w[Q1 Q2 Q3 Q4]

I want to present to user randomly selected one published question from each category of questions. I was trying something like:

CATEGORIES.each { |c| TestQuestion.where(category: c).random }

But I'm getting an error: NoMethodError (undefined method random' for <TestQuestion::ActiveRecord_Relation:0x00007f091cf1ac08>)

Besides I think it's a smelly code. Is there any better way to do that?

there is no random function but you can do (depending on your database)

Postgresql or SQLite:

TestQuestion.where(category: c).order('RANDOM()').first

MySQL:

TestQuestion.where(category: c).order('RAND()').first

you can also use Arel

TestQuestion.where(category: c).order(Arel.sql('RANDOM()')).first

note: that if your DB is large and there is a performance issue you might want to limit(1) then first

you are also using each. which will return the original object you are iterating through, you need to switch to map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM