Skip to content

Instantly share code, notes, and snippets.

@voising
Last active November 14, 2019 09:41
Show Gist options
  • Save voising/a8019f658dd811c90516eba6a26f1bab to your computer and use it in GitHub Desktop.
Save voising/a8019f658dd811c90516eba6a26f1bab to your computer and use it in GitHub Desktop.
Marketplace - Marketplace - Search by rate & tags - Model
# frozen_string_literal: true
# == Schema Information
#
# Table name: products
#
# id :bigint not null, primary key
# user_id :bigint
# title :string
# description :text
# is_listed :boolean
# created_at :datetime not null
# updated_at :datetime not null
#
class Product < ApplicationRecord
# ...
scope :filter_on_rate, lambda {|rate|
min, max = rate
joins(:rates).where('rates.amount': (min.to_f..max.to_f))
}
scope :filter_on_tags, lambda {|kinds, params|
query = joins(:taggables)
.where('taggables.tag_id': kinds.map {|kind| params[kind] }.flatten)
.group("products.id")
kinds.each do |kind|
query = query.having("ARRAY_AGG(taggables.tag_id) && ARRAY[?]::bigint[]", params[kind].map(&:to_i))
end
query
}
# ...
def self.index
select(%(
products.id,
products.user_id,
products.is_listed,
products.title,
products.description,
ARRAY_AGG(DISTINCT taggables.tag_id) AS tag_ids,
MIN(rates.amount) AS amount,
(ARRAY_AGG(attachments.picture))[1] AS attachment
))
.listed
.left_outer_joins([:rates, :taggables, :attachment])
.group("products.id")
.order("products.created_at DESC").limit(100)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment