2

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:

@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.

DGM
  • 26,629
  • 7
  • 58
  • 79
Rails beginner
  • 14,321
  • 35
  • 137
  • 257
  • Are you picking a random column or row? This is slightly confusing... – Jakub Hampl Mar 10 '11 at 18:42
  • 2
    Seems then that all the answers are trying to do random rows. – Jakub Hampl Mar 10 '11 at 18:53
  • FYI, Rails beginner, columns are `name`, `age` and rows are `lars, grete, hans...` so your data has 2 columns and 3 rows. If you want random column, then you will get back text `name` or `age`, NOT it's *values*. – Zabba Mar 10 '11 at 19:07
  • 1
    In that case you have a duplicate: http://stackoverflow.com/questions/3641057/rails-select-random-record or http://stackoverflow.com/questions/2752231/random-record-in-activerecord. – Jakub Hampl Mar 10 '11 at 22:09

4 Answers4

4
@randomname = Model.order('rand()').limit(1).first.name
Kalendae
  • 2,256
  • 1
  • 21
  • 23
3

A random column in Rails 3 is simply:

Model.columns.sample.name
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
1

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

fl00r
  • 82,987
  • 33
  • 217
  • 237
0

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)
Spyros
  • 46,820
  • 25
  • 86
  • 129