Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get two random elements from a RoR model

I'm trying to use RoR for something simple and I'm having some trouble picking up the basics. My closest background is ASP.NET MVC but I'm finding all of the RoR tutorials focus on what rails is really good at (scaffold stuff) but not how to make your own actions and get them to do stuff with parameters etc. (something trivial in ASP.NET MVC).

At the moment I am trying to get two random elements out of the model.

I think I'm dealing with an ActiveRecord collection of some sort?

I have read that there is a .rand method somewhere on collections/arrays, although other places suggest that rand is just a method for getting a random number up to a certain count. I can't even get the following code to work:

def index
    @items = Array.new(Item[0], Item[0])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @domain }
    end
end

Anything that can help with this, and ideally help with further patching from ASP.NET MVC to RoR would be really appreciated.

like image 957
Matt Mitchell Avatar asked Dec 02 '22 08:12

Matt Mitchell


1 Answers

To retrieve two random items from an ActiveRecord model:

@things = Thing.all(:order => 'RANDOM()', :limit => 2)
like image 197
netflux Avatar answered Jan 07 '23 22:01

netflux