0

我有一个模型,我想从中提取符合特定标准的随机记录。例如:给我一个来自 table Thing 的随机记录,其中 column_name = true。

要从模型中获取随机记录,我可以执行以下操作:

Thing.offset(rand(Thing.count)).first

我想将它与查询结合起来:

Thing.where("column_name = ?", true).all

这不起作用:

counter = Thing.where("column_name = ?", true).count
Thing.where("column_name = ?", true).offset(rand(counter)).first

任何关于如何编写此查询的想法将不胜感激。

4

1 回答 1

0

这应该为你做:

  counter = Thing.where("column_name = ?", true).count
  Thing.where("column_name = ?", true).limit("#{rand(counter)}, 1").first

返回从表外某处读取的一行。

于 2012-11-08T13:22:40.547 回答