Rails beginner
Rails beginner

Reputation: 14514

Rails how to randomly pick a row in a table?

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.

Upvotes: 2

Views: 1025

Answers (4)

fl00r
fl00r

Reputation: 83680

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

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40553

A random column in Rails 3 is simply:

Model.columns.sample.name

Upvotes: 3

Kalendae
Kalendae

Reputation: 2244

@randomname = Model.order('rand()').limit(1).first.name

Upvotes: 4

Spyros
Spyros

Reputation: 48686

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)

Upvotes: 0

Related Questions