We have some records loaded from the database (persisted) and some that are in-memory (memory). The same record may be represented in the persisted array and in the memory array.
So the task of this method is to merge them according to the following rules:
* The final array must not have duplicates * The order of the persisted array is to be preserved * Any changes made to attributes on objects in the memory array are to be preserved * Otherwise, attributes should have the value found in the database
# File activerecord/lib/active_record/associations/collection_association.rb, line 398 def merge_target_lists(persisted, memory) return persisted if memory.empty? return memory if persisted.empty? persisted.map! do |record| # Unfortunately we cannot simply do memory.delete(record) since on 1.8 this returns # record rather than memory.at(memory.index(record)). The behavior is fixed in 1.9. mem_index = memory.index(record) if mem_index mem_record = memory.delete_at(mem_index) (record.attribute_names - mem_record.changes.keys).each do |name| mem_record[name] = record[name] end mem_record else record end end persisted + memory end