user3551878
user3551878

Reputation: 1

How to use a random number in a WHERE range?

I want to select all datasets within a range from 0 to a generated random number.

This works:

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

This doesn't work:

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

If I put rand(4) as the upper limit of the range I don't get any result. Why? How can I do it?

Thanks

Edit: Sorry, I was not aware that rand(4) means that 4 is not in the range and that 3 is the maximum result. I solved this now. Thank you.

Upvotes: 0

Views: 98

Answers (3)

paulorcdiniz
paulorcdiniz

Reputation: 164

If you are using Ruby 1.9.3 or greater you can you can use Kernel#rand (wich accepts ranges)

example:

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

edit: as bjhaid pointed out, it was not doing a between query

Upvotes: -2

sp1rs
sp1rs

Reputation: 786

Do something like this ..

a=Random.new

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

or do this ..

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

Upvotes: 1

vee
vee

Reputation: 38645

You won't get any results when rand(4) returns 0.

Try using Array#sample to generate a random number between 1 and 4:

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

Upvotes: 0

Related Questions