【发布时间】:2017-08-25 02:23:46
【问题描述】:
我在 Rails 上使用 ruby,我的产品视图被缓存,我可以通过搜索表单找到产品。我也想使用分页,但是添加后,它不起作用并且还搜索表单。找到了代码行,但不知道怎么用,代码如下。
<% cache ["v1-#{params[:page]-#{params[:q]", cache_key_for_products]
> do %>
我的代码
Index.html.erb
<div class="products">
<div class="container">
<center><h1>All products</h1></center>
<div class="row">
<% cache(cache_key_for_products) do %>
<%= render @products %>
<% end %>
</div>
<%= will_paginate @comments, :container => false %>
</div>
</div>
_product.html.erb
<% cache product do %>
<div class="col-md-3 col-lg-3 col-sm-6 col-xs-12">
<div class="product-block">
<h4 id="product-name"><%= product.name %></h4>
<%= link_to product_path(product), class: 'product_link' do %>
<%= image_tag(product.image_url, class: "img-responsive") %>
<% end %>
<div class="price">
<h4>£ <%= product.price %></h4>
</div>
</div>
</div>
<% end %>
products_helper.rb
module ProductsHelper
def cache_key_for_products
count = Product.count
max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
"products/#{params[:q] || "all"}-#{count}-#{max_updated_at}#{signed_in? && current_user.admin? ? "-admin" : "normal"}"
end
end
products_controller.rb
def index
if params[:q].present?
search_term = params[:q]
if Rails.env.development?
@products = Product.where("name LIKE ?", "%#{search_term}%")
else
@products = Product.where("name ilike ?", "%#{search_term}%")
end
else
@products = Product.all.paginate(:page => params[:page], :per_page => 30)
end
end
【问题讨论】:
-
当您说“它不起作用”时,您能详细说明一下吗?分页是否出现并且不正确?还是没有分页?您的日志中有错误吗?
-
是的,它不起作用。现在我有 5 个产品和分页设置每页 1 个产品。所以现在有 5 页,每页显示所有产品。
标签: ruby-on-rails ruby ruby-on-rails-3 caching pagination