Permalink
Browse files

Reducing SQL calls significantly for collections

  • Loading branch information...
1 parent 2009daa commit 7a8ad204d62bef12a175861026e91043ca7e90cb @jbarket jbarket committed Mar 15, 2012
Showing with 10 additions and 3 deletions.
  1. +7 −2 lib/facet_for.rb
  2. +2 −0 lib/facet_for/form_builder.rb
  3. +1 −1 lib/facet_for/version.rb
View
@@ -106,6 +106,7 @@ def initialize(facet = {})
@facet[:association_name] = "#{association.first.plural_name}"
@facet[:column_name] = "#{association.first.plural_name}_id"
@facet[:clean_column_name] = "#{association.first.name.to_s.singularize}_id"
+ @facet[:association_primary_key] = association.first.primary_key_column.name
elsif association.first.macro == :belongs_to
@@ -114,6 +115,7 @@ def initialize(facet = {})
@facet[:association_class] = association.first.klass
@facet[:association_name] = association.first.name
@facet[:column_name] = association.first.foreign_key
+ @facet[:association_primary_key] = association.first.primary_key_column.name
end
@@ -127,8 +129,11 @@ def initialize(facet = {})
# based on this association. We only want to use distinct values.
# This could probably be cleaner, but it works.
- @facet[:collection] = @facet[:model].unscoped.joins(@facet[:association_name].to_sym).select("DISTINCT #{clean_column}").where("#{clean_column} IS NOT NULL").map { |m| @facet[:association_class].to_s.singularize.camelcase.constantize.find(m.send(clean_column)) }
+ unless @facet[:collection]
+ unique_objects = @facet[:model].unscoped.select("DISTINCT #{clean_column}").where("#{clean_column} IS NOT NULL").map { |x| x.send(clean_column) }.join(", ")
+ @facet[:collection] = @facet[:association_class].unscoped.where("#{@facet[:association_primary_key]} IN (#{unique_objects})")
+ end
end
else
@@ -358,7 +363,7 @@ def clean_column
end
def unique_value_collection
- @facet[:collection] = @facet[:model].unscoped.select("DISTINCT #{clean_column}").where("#{clean_column} IS NOT NULL").map { |m| m.send(@facet[:column_name]) }
+ @facet[:collection] = @facet[:model].unscoped.select("DISTINCT #{clean_column}").where("#{clean_column} IS NOT NULL").map { |x| x.send(clean_column) }
end
def label(string_name, string_label = nil)
@@ -23,6 +23,8 @@ def facet_for(column, *args)
facet[:column_name] = column
facet[:column_type] = options[:column_type]
+ facet[:includes] = options[:includes]
+
# This is the type of field we will render. If this isn't provided, we'll
# determine this based on facet_column_type
View
@@ -1,3 +1,3 @@
module FacetFor
- VERSION = "0.1.3"
+ VERSION = "0.1.4"
end

0 comments on commit 7a8ad20

Please sign in to comment.