开发者

How do I access the nth element in an ruby array? Specifically, a will_paginate collection

I am using ruby on rails and will_paginate to output posts to a page like this:

 <div class="posts">
        <% render @posts %>
 </div>

Let's say I want to change this page so that I render some posts in different divs: <% render 'posts/post', :post => #the first element in the collection %>

 <div class="second_post">
        <% render 'posts/post', :post => #the second element in the collection %>
 </div>
 </div>

 <div class ="lower_container">
 <div class="posts">
        #may have to run a loop for this last one, to render all the rest of posts. How?
        <% render 'posts/post', :post => #all o开发者_运维百科ther posts %>
 </div>
 </div>

Specifically, I know I could use @post.first for the first element, but don't know about the second (or third, or fourth elements). Naturally, my programming background makes me want to do @post(n) where n is the index of the element I want to access. This doesn't work in ruby.

FYI: The post collection is created in the controller by:

  @posts = Post.paginate(:page => params[:page])

Does anyone know how I would best accomplish this goal? I know it may seem unconventional, but for the html/UI aspects I really want to do have the divs like this..


Inside your partial you can call:

<%= posts_counter %>

Or <partial_name>_counter


You could use CSS3's nth-child selectors to target specific div's. For example, if your code looked like:

<div id="posts">
<% @posts.each do |post| %>
  <div>
    <%= post.content %>
  </div>
<% end %>
</div>

Then you can target the first and second <div> like this:

div#posts div:nth-child(1) { }
div#posts div:nth-child(2) { }

jQuery also can select them the same way, and add the classes to them if you require it:

$('div#posts div:nth-child(1)').addClass('firstPost');

Update:

Okay, after your response I'd suggest using the each_with_index helper method when iterating through your collection, like so:

<% @posts.each_with_index do |post, index| %>
  <% if index == 0 %>
    <div class="specialFirstIndexClass">
      <%= post.content %>
    </div>
  <% end %>
  <% if index == 1 %>
    <div class="specialSecondIndexClass">
      <%= post.content %>
    </div>
  <% end %>
<% end %>

Or you could use a Ruby switch like so, as they're pretty:

<% @posts.each_with_index do |post, index| %>
  <% case index %>
  <% when 0 %>
    <div class="specialFirstIndexClass">
      <%= post.content %>
    </div>
  <% when 1 %>
    #etc..
  <% else %>
    <div class="notSoSpecial"><%= post.content %></div>
  <% end %>
<% end %>

Hope this helps :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜