添加分页到现有的Rails站点?

时间:2014-08-25 19:03:21

标签: html ruby-on-rails pagination

所以我有一个包含帖子和类别的Rails应用程序,当我在网站上测试时,我意识到我忘了添加任何分页到类别页面,所以一旦添加了很多列表,页面就会保持不变越来越长,这显然不太理想。

以下是呈现商品详情的每个类别页面上的代码:

<% notsold = @category.products.where("sold_value = false").order("created_at DESC") %>
        <% notsold.each do |f| %>
        <% if User.find(f.user_id).school == current_user.school %>
          <div class="listing">
            <a href="/users/<%= f.user_id %>" class="nounderline"><%= image_tag User.find(f.user_id).avatar.url(:thumb).sub('http://s3.amazonaws.com/anymarket/','http://anymarket.s3.amazonaws.com/'), :id => "categories_profile_picture", :width => "30", :height => "30" %></a><h4><%= link_to f.name, view_item_path(f.id) %></h4><% if f.photo? %><span id="camera-icon-preview" class="glyphicon glyphicon-camera preview_toggle" data-id="<%= f.id %>"></span><% else %><% end %><p><%= f.description[0..60].gsub(/\s\w+\s*$/, '...') %></p><p class="price"><%= number_to_currency(f.decimal_price, precision: 2) %></p>
          </div>
      <% else %>
      <% end %>
  <% end %>

Div#listing是每个列表。

问题是我不知道如何保存此代码并添加分页。我正在寻找关于如何做到这一点的一些建议。

1 个答案:

答案 0 :(得分:1)

您可以使用will_paginate gem

来自页面的示例: 在你的控制器中这样:

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

更多例子:

## perform a paginated query:
@posts = Post.paginate(:page => params[:page])

# or, use an explicit "per page" limit:
Post.paginate(:page => params[:page], :per_page => 30)

## render page links in the view:
<%= will_paginate @posts %>

不确定,但这应该适合你:

<% notsold = @category.products.where("sold_value = false").order("created_at DESC").paginate(:page => params[:page], :per_page => 30) %>
        <% notsold.each do |f| %>
        <% if User.find(f.user_id).school == current_user.school %>
          <div class="listing">
            <a href="/users/<%= f.user_id %>" class="nounderline"><%= image_tag User.find(f.user_id).avatar.url(:thumb).sub('http://s3.amazonaws.com/anymarket/','http://anymarket.s3.amazonaws.com/'), :id => "categories_profile_picture", :width => "30", :height => "30" %></a><h4><%= link_to f.name, view_item_path(f.id) %></h4><% if f.photo? %><span id="camera-icon-preview" class="glyphicon glyphicon-camera preview_toggle" data-id="<%= f.id %>"></span><% else %><% end %><p><%= f.description[0..60].gsub(/\s\w+\s*$/, '...') %></p><p class="price"><%= number_to_currency(f.decimal_price, precision: 2) %></p>
          </div>
      <% else %>
      <% end %>
  <% end %>