简体   繁体   English

Rails 6 select 随机 ActiveRecord object 每个类别

[英]Rails 6 select random ActiveRecord object for each category

I've got TestQuestion model where I store survey questions with predefined and hardcoded categories:我有 TestQuestion model 我在其中存储带有预定义和硬编码类别的调查问题:

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>)但我收到一个错误: 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)没有随机 function 但你可以做(取决于你的数据库)

Postgresql or SQLite: Postgresql 或 SQLite:

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

MySQL: MySQL:

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

you can also use Arel你也可以使用 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注意:如果您的数据库很大并且存在性能问题,您可能想要limit(1) ,那么first

you are also using each.你也在使用each. which will return the original object you are iterating through, you need to switch to map.这将返回您正在迭代的原始 object,您需要切换到map.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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