views:

27

answers:

3

Hey, So I am generating XML data in my RoR application for an external source to consume. The method in my controller is as follows...

def allOffers
 @ridesall = Ride.find(:all)
respond_to do |format|
    format.xml   
 end
end

I have a allOffers.xml.builder file that looks like this...

xml.instruct!
xml.rides do
@ridesall.each do |ride|
  xml.item("togive" => ride.togive, "totake" => ride.totake, "howlong" => ride.howlong, "isoffer" => ride.isoffer, "id" => ride.id, "contact" => ride.contact)
  end
end

This works great except for one thing...it orders the xml based on ID. How can i get the xml to be order randomly?

Can I simply change

@ridesall = Ride.find(:all)

to

@ridesall = Ride.find(:all, :order => :random)

?

Thanks

+1  A: 

What database are you using? You'll probably need to rely on an RDBMS-specific random function. For example in mysql

:order => 'rand()'

or in postgresql

:order => 'random()'
mopoke
+1  A: 

You can shuffle the array itself. This will work for any kind of database.

@ridesall.shuffle.each do
  #...
end

Note: Array#shuffle is new to 1.8.7, so require 'backports' if using Ruby 1.8.6.

Marc-André Lafortune
A: 

@ridesall.sort_by { |x| rand() } works too

Mike H