【问题标题】:How to use a random number in a WHERE range?如何在 WHERE 范围内使用随机数?
【发布时间】:2014-04-19 14:36:07
【问题描述】:

我想选择从 0 到生成的随机数范围内的所有数据集。

这行得通:

@test = Test.where( :level => 0..4 )

这不起作用:

@test = Test.where( :level => 0..rand(4) )

如果我将 rand(4) 作为范围的上限,我不会得到任何结果。为什么?我该怎么做?

谢谢

编辑:抱歉,我不知道 rand(4) 表示 4 不在范围内,而 3 是最大结果。我现在解决了这个问题。谢谢。

【问题讨论】:

  • 试试这个@test = Test.where( :level => rand(0..4) )
  • 你说的不能正常工作,我刚刚从 Rails 控制台测试过,你能发布你遇到的错误

标签: ruby-on-rails ruby


【解决方案1】:

做这样的事情..

a=Random.new

@test = Test.where(:level=>0..(x*a.rand))   # where x is the no of level .

或者这样做..

@test= Test.where (:level=>0..a.integer(x))  # where x is same as above

【讨论】:

    【解决方案2】:

    当rand(4) 返回0 时,您不会得到任何结果。

    尝试使用Array#sample 生成1到4之间的随机数:

    @test = Test.where( :level => 0..(1..4).to_a.sample )
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 Ruby 1.9.3 或更高版本,您可以使用 Kernel#rand(接受范围)

      示例:

      @test = Test.where(id: 0..rand(0..4))
      

      编辑:正如 bjhaid 指出的那样,它没有在查询之间进行

      【讨论】:

      • 这不会做between查询
      • 你是绝对正确的。我试过了,这有效 Test.where(id: 0..rand(0..4))
      猜你喜欢
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2015-06-21
      • 1970-01-01
      相关资源
      最近更新 更多