Re: RANDOM

Mason K. wrote:

I have a set of Sponsors that I would like to be able to select one at
random and display in the my html. I have already set up the DB,
scaffolded, set index controller and all is working smoothly.

I know that I can display them all by doing

<% for sponsor in @sponsors %>

<%= sponsor.name %>

<% end %>

How can I just select one of the sponsors to display each time someone
hits this page?

<%= @sponsors[(rand*(@sponsors.size-1)).round] %>

or make a method in your Sponsor model to be DRYer:

def self.random
find(:all)[(rand*(count-1)).round]
end

and then you can say @sponsor = Sponsor.random or whatever.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs