开发者

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


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) %>


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)  %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜