从包含许多pg_search查询获取对象计数

时间:2018-03-14 14:08:53

标签: ruby-on-rails ruby-on-rails-5

我在productvariation模型之间有很多关系。我还使用pg_search来帮助过滤搜索结果。

我需要显示已过滤搜索结果中的产品总数以及这些过滤产品的变体总数。

product.rb

class Product < ApplicationRecord
  ...
  include PgSearch
  pg_search_scope :search_for,
                  against: %i(name body),
                  associated_against: { variations: :name, categories: :name, tags: :name },
                  using: {
                      tsearch: {
                          any_word: true
                      }
                  }


  has_many :variations, -> { order(:order) }, dependent: :destroy
  ...
end

variation.rb

class Variation < ApplicationRecord
  ...
  has_many :products
  ...
end

products_controller.rb 下面的@total_items我无法弄清楚如何参与(参数[:查询])

...
def index
      if params[:query]
        @products = Product.search_for(params[:query])
        @total_collections = Product.search_for(params[:query]).count
        @total_items = Variation.joins(:product).count
      else
        ...
      end
end
...

0 个答案:

没有答案