How do I random pick a row in a table?
Example my table:
name age
Lars 24
Grete 56
Hans 56
I want to random pick a name.
Example:
开发者_StackOverflow中文版@randomname = Model.where(:name 'Random')
And how do I only pick 1 random name each day. That I can use as a instant variable in view.
@randomname = Model.order('rand()').limit(1).first.name
A random column in Rails 3 is simply:
Model.columns.sample.name
If you want to get random object 1 per day, so you should store it somewhere. You can store it:
- in separate file
- in separate model
- in the same model add rndm field
Lets implement the last one. It is quite easy. Imagine, that your Model
called User
. First, let's add new date field rndm
:
rails g migration add_rndm_to_user rndm:date
rake db:migrate
Now we need to add some methods to your User
model
class User < ActiveRecord::Base
def self.random
rndm = find_by_rndm Date.today
unless rndm
update_all :rndm => nil
rndm = self.order('rand()').first
rndm.update_attribute :rndm, Date.today
end
rndm
end
end
so now you can call User.random
from your controller
I have some Rails 2 code that shows the idea i think, and it's very easy to convert to rails 3 :
random_monsters = self.find(:all, :conditions=>["level > 0 and level < ? and monster_type='monster'", user_level+2])
random_monster = random_monsters[rand(random_monsters.length)]
I've also seen somebody in SO propose an offset way like :
offset = rand(Model.count)
rand_record = Model.first(:offset => offset)
精彩评论