Ruby on rails 如何访问ruby数组中的第n个元素?具体地说,一个将对集合进行分页
我正在使用ruby on rails,并将分页以将帖子输出到如下页面:Ruby on rails 如何访问ruby数组中的第n个元素?具体地说,一个将对集合进行分页,ruby-on-rails,arrays,ruby-on-rails-3,loops,pagination,Ruby On Rails,Arrays,Ruby On Rails 3,Loops,Pagination,我正在使用ruby on rails,并将分页以将帖子输出到如下页面: <div class="posts"> <% render @posts %> </div> div#posts div:nth-child(1) { } div#posts div:nth-child(2) { } 有人知道我怎样才能最好地实现这个目标吗?我知道这可能看起来很不传统,但对于html/UI方面,我真的很想让div像这样..在您的部分中,您可以调用:
<div class="posts">
<% render @posts %>
</div>
div#posts div:nth-child(1) { }
div#posts div:nth-child(2) { }
有人知道我怎样才能最好地实现这个目标吗?我知道这可能看起来很不传统,但对于html/UI方面,我真的很想让div像这样..在您的部分中,您可以调用:
<%= posts_counter %>
或者_counter您可以使用CSS3的第n个子选择器以特定的div为目标。例如,如果您的代码看起来像:
<div id="posts">
<% @posts.each do |post| %>
<div>
<%= post.content %>
</div>
<% end %>
</div>
jQuery也可以用同样的方法选择它们,并在需要时向它们添加类:
$('div#posts div:nth-child(1)').addClass('firstPost');
更新:
好的,在您的回答之后,我建议在遍历集合时使用each_with_index helper方法,如下所示:
<% @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 %>
或者您可以使用这样的Ruby开关,因为它们很漂亮:
<% @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 %>
希望这能有所帮助:我知道rails中有一个鲜为人知的功能,可以将一个集合呈现为多个列,但我的google fu无法回答您的问题。不幸的是,这还不够——我想把div放在不同的容器div中,所以仅仅更改它们的属性是不够的,我将编辑这个问题。考虑到这一点,有什么想法吗?@geb2011:嘿,我更新了我的答案,我想每个带有索引的_都是你想要的。
<% @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 %>
<% @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 %>