Ruby rand() cannot accept variables? -
i'm little baffled this.
my end goal in ror project grab single random profile database.
i thinking like:
@profile = profile.find_by_user_id(rand(user.count))
it kept throwing error because user_id
0 doesn't exist, pulled parts of out check out what's going on:
@r = rand(user.count) <%= @r %>
this returns 0 every time. what's going on? registered 5 fake users , 5 related profiles test this.
if take profile.find_by_user_id(rand(user.count))
, rewrite
profile.find_by_user_id(3)
it works fine.
user.count
working too. think rand()
can't take input other static integer.
am right? whats going on?
try:
profile.first(:offset => rand(profile.count))
as database ages, 1 user records, there gaps in id field sequence. trying grab id @ random have potential fail because might try randomly grab 1 deleted.
instead, if count number of records, randomly go offset table sidestep possibility of having missing ids, , landing on existing records.
the following example ops question run problems unless integrity of database watched carefully:
profile = profile.find_by_user_id(rand(user.count))
the problem is, there's possibility user table out of sync profile table, allowing them have different numbers of records. instance, if user.count
3 , there 2 records in profile there's potential failed lookup resulting in exception.
Comments
Post a Comment