Rails局部视图重复显示

时间:2015-08-07 15:02:01

标签: ruby-on-rails partial-views erb

以下是我index.html

的一部分
<div class="col-md-8">
        <% @books.each do |book| %>
          <div class="row">

            <div class="col-md-4">
              <%= image_from_amazon(book.amazon_id) %>
            </div>
            <div class="col-md-8">
                <h3 class = "text-info">
                   <%= book.title %>
                </h3>
                 <br>
                <em class ="text-muted">
                    written by <%= book.author %>
                </em>
                <br>
                 <br>
                <p>
                    <%= book.description %>
                </p>
                <% book.genres.each do |genres| %> 
                    <span class="label label-primary">
                     <%= genres.name %> 
                    </span>
                    &nbsp
                <% end %>
              </div>
           </div>  
        <% end %>
        </div>

基本上,它会显示3本书,并且工作正常。

然后,我将该代码移至_book.html.erb并将上述代码编辑为

<%= render @books %>

然而,重复3次,即显示9本书。并且顺序是[第1,第2,第3] [第1,第2,第3] [第1,第2,第3]像这张照片。 enter image description here

更新

更新 index.html.erb

 <div class="clearfix">
   <div class="col-md-12">
     <%= render @books %>

          <div class="col-md-4">
              <h3>Genre (Click to filter books)</h3>
              <br>
             <li>
             <span class = 'label label-danger'>
              <%= link_to "No filter" ,books_path, style: 'color:#FFFFFD' %>
             </span>
             <br>
             <br>
             </li>

              <% @genres.each do |genres| %>
              <li>
                <span class = 'label label-primary'  style="color:#FFFFFD">
                  <%= link_to genres.name ,books_path(filter: genres.name),style: 'color:#FFFFFD' %>
                </span>
              </li>
              <br>
              <% end %>
          </div>
        </div>
<!-- clearfix -->
 </div>

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

<div class="col-md-8">
    <%= render @books %>
</div>

并确保<% @books.each do |book| %>及其<% end %>标记不在部分内。

Rendering Collections Docs

修改

#index.html.erb
<div class="col-md-8">
    <%= render @books %>
</div>

# _book.html.erb
<div class="row">
    <div class="col-md-4">
        <%= image_from_amazon(book.amazon_id) %>
    </div>
    <div class="col-md-8">
        <h3 class = "text-info">
            <%= book.title %>
        </h3>
        <br>
        <em class ="text-muted">
            written by <%= book.author %>
        </em>
        <br>
        <br>
        <p>
            <%= book.description %>
        </p>
        <% book.genres.each do |genres| %> 
        <span class="label label-primary">
            <%= genres.name %> 
        </span>
        &nbsp
        <% end %>
    </div>
</div>