【问题标题】:PostgreSQL Queries - Spree product filtering methods and associationsPostgreSQL 查询 - 大礼包产品过滤方法和关联
【发布时间】:2015-12-02 09:19:22
【问题描述】:

我正在尝试为产品添加一些过滤,但我的查询非常丑陋和繁重..

您将如何改进此查询? (想要退回没有翻译或有但字段为空的产品)

Spree::Product.all.map { |p| p if !p.translations.find_by(locale: 'en') || (p.translations.find_by(locale: 'en') && p.translations.find_by(locale: 'en').name.blank?) }.reject(&:blank?)
# takes about 1 second

另一个查询是关于与产品相关的分类单元:

Spree::Product.all.map { |p| p unless p.taxons.any? }.reject(&:blank?)

我知道有一种方法可以返回没有任何关联 has_many 记录的记录,例如:Spree::Product.all.includes(:taggings).where(taggings: { taggable_id: nil })。但由于某种原因,它不想使用分类单元。

我还想知道是否有办法改进对模型方法的查询。例如,我有一个查询返回所有没有图片的产品:

Spree::Product.all.map { |p| p unless p.all_images.any? }.reject(&:blank?)
# takes over 2 seconds

# product_decorator.rb
def all_images
  (images + variant_images).uniq
end

谢谢!

【问题讨论】:

    标签: sql ruby-on-rails postgresql spree


    【解决方案1】:

    当您使用.all 时,它将加载所有记录并执行您在块中设置的那些操作({})。尝试使用纯SQL 或更好的方式挂载查询,使用.where 子句,它将挂载您的查询并且性能会更好。您可以使用多个.where,一个接一个地链接方法。

    您可以在Rails guide找到更多关于条件的信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多