1

I am trying to fetch a random record in rails, to render in my home page.

I have a post model with content and title attributes. Lets say i wanted to fetch a random post(content and title) for some reason, How can i go about it in ruby. Thanks in advance.

m_x
  • 12,357
  • 7
  • 46
  • 60

5 Answers5

4

You might find this gem handy : Faker

It allows to generate random strings with some meaning.

For example, a name :

Faker::Name.name => “Bob Hope”

Or an e-mail

Faker::Internet.email

In addition to this gem, if you want to be able to generate mock models very easily, I recommend the gem Factory Girl

It allows you to create factories for your model, sou you can generate a model with random attributes quickly.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
  • Thanks for getting back to me and Sorry if i was unclear, I want to fetch a random post not create. If i am correct the faker gem creates random attributes. I am looking for fetch attributes at random to render in a view. –  Mar 03 '13 at 15:22
1

Posting another answer since the first one answered to an unclear question.

As @m_x said, you can use RANDOM() for SQL.

If you don't mind loading all the dataset, you can do it in ruby as well :

Post.all.sample 

This will select one random record from all Posts.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
1

I know this is an old question, but since no answer was chosen, answering it might be helpful for other users.

I think the best way to go would be generating a random offset in Ruby and using it in your Active Record statement, like so:

Thing.limit(1).offset(rand(Thing.count)).first

This solution is also performant and portable.

CodeBender
  • 67
  • 9
0

In your post controller,

def create
  @post = Post.new(params[:post])
  if you_want_some_random_title_and_content
    title_length = 80 #choose your own
    content_length = 140 #choose your own
    @post.title = (0...title_length).map{(65+rand(26)).chr}.join
    @post.content = (0...content_length).map{(65+rand(26)).chr}.join
  end

  if @post.save
    redirect_to @post
  else
    render 'new'
  end
end

Using Kent Fedric's way to generate random string

Community
  • 1
  • 1
Jason Kim
  • 18,102
  • 13
  • 66
  • 105
0

unfortunately, there is no database-agnostic method for fetching a random record, so ActiveRecord does not implement any.

For postgresql you can use :

Post.order( 'RANDOM()' ).first

To fetch one random post.

Additionnally, i usually create a scope for this:

class Post < ActiveRecord::Base
  scope :random_order, ->{ order 'RANDOM()' }
end

so if you change your RDBMS, you just have to change the scope.

m_x
  • 12,357
  • 7
  • 46
  • 60