Skip to content

Instantly share code, notes, and snippets.

@jturkel
Last active March 1, 2017 04:47
Show Gist options
  • Save jturkel/7917985 to your computer and use it in GitHub Desktop.
Save jturkel/7917985 to your computer and use it in GitHub Desktop.
CREATE VIEW product_stats AS
SELECT organization_id,
SUM(CASE WHEN status = 'active' THEN 1 END) active_count,
SUM(CASE WHEN status = 'inactive' THEN 1 END) inactive_count
FROM products
GROUP BY organization_id
class ProductSummary < ActiveRecord::Base
include ReadOnlyModel
belongs_to :organization
def ==(other)
self.class == other.class && attributes == other.attributes
end
alias :eql? :==
def hash
attributes.hash
end
end
class ProductSummary < ActiveRecord::Base
include ReadOnlyModel
belongs_to :organization
default_scope { set_from_clause }
def ==(other)
self.class == other.class && attributes == other.attributes
end
alias :eql? :==
def hash
attributes.hash
end
private
def self.set_from_clause
query = Product.select(:organization_id).group(:organization_id)
Product::VALID_STATUSES.each do |status|
query = query.select("SUM(CASE WHEN status = '#{status}' THEN 1 END) #{status}_count")
end
from("(#{query.to_sql}) AS #{table_name}")
end
def self.columns
cols = [ActiveRecord::ConnectionAdapters::Column.new('organization_id', nil, :integer)]
Product::VALID_STATUSES.each do |status|
cols << ActiveRecord::ConnectionAdapters::Column.new("#{status}_count", nil, :integer)
end
cols
end
end
org_infos = Organization.limit(25).map do |org|
{
id: org.id,
name: org.name,
active_product_count: org.products.active.count,
inactive_product_count: org.products.inactive.count
}
end
class Organization < ActiveRecord::Base
has_many :products
end
class Organization < ActiveRecord::Base
has_many :products
has_one :product_summary
end
class Product < ActiveRecord::Base
belongs_to :organization
VALID_STATUSES = [:active, :inactive]
scope :active, where(state: :active)
scope :inactive, where(state: :inactive)
end
org_infos = Organization.includes(:product_summary).limit(25).map do |org|
{
id: org.id,
name: org.name,
active_product_count: org.product_summary.active_count,
inactive_product_count: org.product_summary.inactive_count
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment