将数组显示到列

时间:2013-04-10 09:49:42

标签: ruby-on-rails arrays ruby-on-rails-3.2

我试过https://stackoverflow.com/a/4103220/1297435

<% Room.all.in_groups_of(1).each do |room_array| %>
      <% room_array.each do |room| %>
      <%= check_box_tag "student[room_ids][]", room.id, @student.room_ids.include?(room.id), id: dom_id(room) %> <%= label_tag dom_id(room), room.name %><br>
      <% end %>
    <% end %>

当我将in_groups_of(1)更改为in_groups_of(5)时,我收到了错误

  

如果你真的想要的话,被称为nil的id,这将错误地为4   nil的id,使用object_id

更新

<% Room.all.in_groups_of(5).each do |room_array| %>
          <% room_array.compact.each do |room| %>
          <%= check_box_tag "student[room_ids][]", room.id, @student.room_ids.include?(room.id), id: dom_id(room) %> <%= label_tag dom_id(room), room.name %><br>
          <% end %>
        <% end %>

为什么不显示到列?

enter image description here

1 个答案:

答案 0 :(得分:1)

in_groups_of方法使用nil对象填充数组,当数组中的对象数较少时。所以你需要在渲染之前删除nil。

使用compact删除nil对象

<% Room.all.in_groups_of(1).each do |room_array| %>
      <% room_array.compact.each do |room| %>
      <%= check_box_tag "student[room_ids][]", room.id, @student.room_ids.include?(room.id), id: dom_id(room) %> <%= label_tag dom_id(room), room.name %><br>
      <% end %>
    <% end %>