diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2004-12-07 12:25:01 +0000 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2004-12-07 12:25:01 +0000 |
commit | ea759cb76161a7a0003c3cd3b38a8a125a99af3c (patch) | |
tree | 468f4ba7ea4f4b3cb778906fa1c9ebb680f4944f /activerecord/lib/active_record/associations | |
parent | 465e0c0c2635588927ca707e6220cd7f232b3f17 (diff) | |
download | rails-ea759cb76161a7a0003c3cd3b38a8a125a99af3c.tar.gz rails-ea759cb76161a7a0003c3cd3b38a8a125a99af3c.tar.bz2 rails-ea759cb76161a7a0003c3cd3b38a8a125a99af3c.zip |
Added counter_sql option for has_many associations [bitsweat]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@68 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib/active_record/associations')
-rw-r--r-- | activerecord/lib/active_record/associations/has_many_association.rb | 18 |
1 files changed, 12 insertions, 6 deletions
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 947862ad37..0f2d20d240 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -7,9 +7,15 @@ module ActiveRecord if options[:finder_sql] @finder_sql = interpolate_sql(options[:finder_sql]) - @counter_sql = @finder_sql.gsub(/SELECT (.*) FROM/i, "SELECT COUNT(*) FROM") else - @finder_sql = "#{@association_class_primary_key_name} = '#{@owner.id}' #{@conditions ? " AND " + interpolate_sql(@conditions) : ""}" + @finder_sql = "#{@association_class_primary_key_name} = '#{@owner.id}' #{@conditions ? " AND " + interpolate_sql(@conditions) : ""}" + end + + if options[:counter_sql] + @counter_sql = interpolate_sql(options[:counter_sql]) + elsif options[:finder_sql] + @counter_sql = options[:counter_sql] = @finder_sql.gsub(/SELECT (.*) FROM/i, "SELECT COUNT(*) FROM") + else @counter_sql = "#{@association_class_primary_key_name} = '#{@owner.id}'#{@conditions ? " AND " + interpolate_sql(@conditions) : ""}" end end @@ -70,21 +76,21 @@ module ActiveRecord @association_class.find_all(@finder_sql, @options[:order] ? @options[:order] : nil) end end - + def count_records if has_cached_counter? @owner.send(:read_attribute, cached_counter_attribute_name) - elsif @options[:finder_sql] + elsif @options[:counter_sql] @association_class.count_by_sql(@counter_sql) else @association_class.count(@counter_sql) end end - + def has_cached_counter? @owner.attribute_present?(cached_counter_attribute_name) end - + def cached_counter_attribute_name "#{@association_name}_count" end |