How to paginate sunspot in this manner?

2020-07-27 04:15发布

问题:

I have the following model associations:

class Product < ActiveRecord::Base
  has_many :prices

class Price < ActiveRecord::Base
  belongs_to :product

Here is my controller

class SearchController < ApplicationController

  # Using Sunspot here.
  def index
    @search = Product.search do
      fulltext params[:search]
      paginate(:per_page => 5, :page => params[:page])
    end
    @products = @search.results
  end
end

and then my view:

<%= will_paginate @products %>
<% @products.each do |product| %>
    <%= product.name %>
  <% prices.each do |price| %>
    <%= price.price %>
  <% end %>
<% end %>

Lets say I have 10 Products that each have 20 different Prices. My goal is to show 5 Products per page but have the Prices run over to the next page if the amount of Prices on a page exceeds a maximum of 25 at a time.

Here is two different examples of what I want it to do:

 Product 1, 2, 3, 4 + 5 Prices each = same page
 Product 5 + 6 Prices = this Product with Prices on next page

Or

Product 1 + 23 prices = same page
Product 2 + 20 prices = next page with Product and prices

How can I achieve this?

回答1:

The first thing that comes to my mind is to query over the Price model:

prices = Price.joins(:product).where(:product_id => [1,2,3]).paginate(:page => params[:page])

And to make things easier for your views: prices.map! { |p| p.product }