Search code examples
databaseruby-on-rails-3randomrandom-access

Rails 3: Display 1 Random Item from Database: Question_Edit:more_detailed


Edit: More Detailed and to the point

I'm using Rails 3:

I currently have a list of items that are being pulled from my database and displayed on the properties/index page where people can see basic information and then click its link to go to the properties/show page. the code I'm using to call this is

<% @properties.each do |property| %>
<%= link_to property.title,  link_to_rental(property)  %>
<% end %>

The link_to_rental(property) is defined in the Properties Helper

What I'd like to do, is have a featured property on my home/index page. Is there a way to use something similar that pulls one property at random from the property controller and display its .title on the home/index page?

note: rand is deprecated in rails 3 must use random_element


Solution

  • In the home controller it looks like I needed to add an array for the properties first, and then create the array to randomize the list of properties. for example:

    properties = Property.joins(:status).where(:statuses => { :available => 'Not-Rented'})
    @property = properties[rand(properties.count)]
    
      respond_to do |format|
        format.html # index.html.erb
        format.xml  { render :xml => @properties }
      end
    

    Leaving us with this to use on the home/index view:

    <%= link_to @property.title,  link_to_rental(@property)  %>