diff options
Diffstat (limited to 'activerecord/lib/active_record/associations/association_collection.rb')
-rw-r--r-- | activerecord/lib/active_record/associations/association_collection.rb | 36 |
1 files changed, 26 insertions, 10 deletions
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb index 268452f422..e705576120 100644 --- a/activerecord/lib/active_record/associations/association_collection.rb +++ b/activerecord/lib/active_record/associations/association_collection.rb @@ -9,7 +9,7 @@ module ActiveRecord end def reset - @target = [] + reset_target! @loaded = false end @@ -28,7 +28,7 @@ module ActiveRecord callback(:after_add, record) end end - + result && self end @@ -39,7 +39,7 @@ module ActiveRecord def delete_all load_target delete(@target) - @target = [] + reset_target! end # Remove +records+ from this association. Does not destroy +records+. @@ -77,9 +77,9 @@ module ActiveRecord each { |record| record.destroy } end - @target = [] + reset_target! end - + def create(attributes = {}) # Can't use Base.create since the foreign key may be a protected attribute. if attributes.is_a?(Array) @@ -95,21 +95,21 @@ module ActiveRecord # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length. def size - if loaded? then @target.size else count_records end + if loaded? && !@reflection.options[:uniq] then @target.size else count_records end end - + # Returns the size of the collection by loading it and calling size on the array. If you want to use this method to check # whether the collection is empty, use collection.length.zero? instead of collection.empty? def length load_target.size end - + def empty? size.zero? end - + def uniq(collection = self) - collection.inject([]) { |uniq_records, record| uniq_records << record unless uniq_records.include?(record); uniq_records } + collection.to_set.to_a end # Replace this collection with +other_array+ @@ -127,6 +127,22 @@ module ActiveRecord end end + protected + def reset_target! + @target = Array.new + end + + def find_target + records = + if @reflection.options[:finder_sql] + @reflection.klass.find_by_sql(@finder_sql) + else + find(:all) + end + + @reflection.options[:uniq] ? uniq(records) : records + end + private # Array#flatten has problems with recursive arrays. Going one level deeper solves the majority of the problems. def flatten_deeper(array) |