53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
# File 'lib/acts_as_taggable_on/acts_as_taggable_on/collection.rb', line 53
def all_tag_counts(options = {})
options.assert_valid_keys :start_at, :end_at, :conditions, :at_least, :at_most, :order, :limit, :on, :id
scope = if ActiveRecord::VERSION::MAJOR >= 3
{}
else
scope(:find) || {}
end
options[:conditions] = sanitize_sql(options[:conditions]) if options[:conditions]
start_at_conditions = sanitize_sql(["#{Tagging.table_name}.created_at >= ?", options.delete(:start_at)]) if options[:start_at]
end_at_conditions = sanitize_sql(["#{Tagging.table_name}.created_at <= ?", options.delete(:end_at)]) if options[:end_at]
taggable_conditions = sanitize_sql(["#{Tagging.table_name}.taggable_type = ?", base_class.name])
taggable_conditions << sanitize_sql([" AND #{Tagging.table_name}.taggable_id = ?", options.delete(:id)]) if options[:id]
conditions = [
taggable_conditions,
options[:conditions],
scope[:conditions],
start_at_conditions,
end_at_conditions
].compact.reverse
tagging_join = "LEFT OUTER JOIN #{Tagging.table_name} ON #{Tag.table_name}.id = #{Tagging.table_name}.tag_id"
tagging_join << sanitize_sql([" AND #{Tagging.table_name}.context = ?", options.delete(:on).to_s]) if options[:on]
taggable_join = "INNER JOIN #{table_name} ON #{table_name}.#{primary_key} = #{Tagging.table_name}.taggable_id"
taggable_join << " AND #{table_name}.#{inheritance_column} = '#{name}'" unless descends_from_active_record?
joins = [
tagging_join,
taggable_join,
scope[:joins]
].compact.reverse
scope = Tag.scoped(:select => "#{Tag.table_name}.*, COUNT(*) AS count").order(options[:order]).limit(options[:limit])
joins.each { |join| scope = scope.joins(join) }
conditions.each { |condition| scope = scope.where(condition) }
at_least = sanitize_sql(['COUNT(*) >= ?', options.delete(:at_least)]) if options[:at_least]
at_most = sanitize_sql(['COUNT(*) <= ?', options.delete(:at_most)]) if options[:at_most]
having = [at_least, at_most].compact.join(' AND ')
if ActiveRecord::VERSION::MAJOR >= 3
scoped_select = "#{table_name}.#{primary_key}"
scope = scope.where("#{Tagging.table_name}.taggable_id IN(#{select(scoped_select).to_sql})")
having = having.blank? ? "COUNT(*) > 0" : "COUNT(*) > 0 AND #{having}"
scope = scope.group(grouped_column_names_for(Tag)).having(having)
else
group_by = "#{grouped_column_names_for(Tag)} HAVING COUNT(*) > 0"
group_by << " AND #{having}" unless having.blank?
scope = scope.group(group_by)
end
scope
end
|