Ruby rand () cannot accept variables?

I am a little puzzled by this.

My ultimate goal in a RoR project is to grab one random profile from my database.

I thought it would be something like:

@profile = Profile.find_by_user_id(rand(User.count))

He kept throwing an error because user_id0 does not exist, so I pulled out parts of it to check what was going on:

@r = rand(User.count)

<%= @r %>

This returns 0 every time. So what is going on? I registered 5 fake users and 5 related profiles to verify this.

If I take Profile.find_by_user_id(rand(User.count))and rewrite it as

Profile.find_by_user_id(3)

It works great.

User.countalso works. Therefore, I think that rand()it cannot accept an input other than a static integer.

I'm right? What's happening?

+5
source share
4

Try:

Profile.first(:offset => rand(Profile.count))

, , . , .

, , - , .

OPs , :

profile = Profile.find_by_user_id(rand(User.count))

, "" "", . , User.count 3, , .

+9

, rand (i) , ( ), ; - , , .

, Rails ActiveRecord. Profile.find_all() , , , -

@profile = Profile.find_by_sql("SELECT * FROM profiles ORDER BY RAND() LIMIT 1").first

StackOverflow , SQL; , , , , , .

EDIT: find_by_sql , .first .

+4

Rails, - :

@profile = Profile.first(:order => "RAND()")

, , , RAND() MySQL , , . RANDOM().

+1

ID IN Rails

@profile = Profile.find_by_user_id(rand(User.count))
#This is redudent, all you need to code is: 
@profile = Profile.find(rand(User.count)) #default for Rails is ID

An error message based on 0is probably due to RAILS with Conventions Over Configurationreasonable defaults that are correct that people agree about.

And when using rails there is no reason to have a user as 0, it always starts with 1, which I refer to DHH to be more readable.

-3
source

All Articles