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

957 views Asked by At

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

2

There are 2 answers

0
mediarts On BEST ANSWER

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)  %>
2
seeingidog On

It's probably best to put the logic in your controller:

@randitem = @items[rand(items.count)]

Then the view:

<%= link_to @randitem.name_of_item, link_to_item(@randitem) %>