【问题标题】:Rails Active Record Query - find random record that meets a conditionRails Active Record Query - 查找满足条件的随机记录
【发布时间】:2012-11-08 12:44:55
【问题描述】:

我有一个模型,我想从中提取满足特定条件的随机记录。例如:给我一个来自表 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

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

【问题讨论】:

  • 您尝试实现的实际查询是什么。您实际上有一个名为“things”的表,其中包含一个名为“'column_name'”的布尔列。我知道您在发布时可能更改了这些值名称,但由于您没有提供堆栈跟踪或任何相关信息,因此很难提供你的帮助
  • 刚刚尝试了您的代码并适应了我的应用程序,它运行良好......错误是什么?
  • 你是对的。我又试了一次,它正在工作。不知道我上次做错了什么。

标签: ruby-on-rails ruby-on-rails-3 activerecord random


【解决方案1】:

这应该为你做:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多