Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何访问ruby数组中的第n个元素?具体地说,一个将对集合进行分页_Ruby On Rails_Arrays_Ruby On Rails 3_Loops_Pagination - Fatal编程技术网

Ruby on rails 如何访问ruby数组中的第n个元素?具体地说,一个将对集合进行分页

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像这样..在您的部分中,您可以调用:

我正在使用ruby on rails,并将分页以将帖子输出到如下页面:

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