开发者

Ordering XML data randomly generated from RoR

So I am generating XML data in my RoR application for an external source to consume. The meth开发者_Python百科od 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


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()'


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜