Method: ActiveRecord::Associations::CollectionProxy#replace
- Defined in:
- activerecord/lib/active_record/associations/collection_proxy.rb
#replace(other_array) ⇒ Object
Replaces this collection with other_array. This will perform a diff and delete/add only records that have changed.
class Person < ActiveRecord::Base
has_many :pets
end
person.pets
# => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
other_pets = [Pet.new(name: 'Puff', group: 'celebrities')]
person.pets.replace(other_pets)
person.pets
# => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
If the supplied array has an incorrect association type, it raises an ActiveRecord::AssociationTypeMismatch error:
person.pets.replace(["doo", "ggie", "gaga"])
# => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
391 392 393 |
# File 'activerecord/lib/active_record/associations/collection_proxy.rb', line 391 def replace(other_array) @association.replace(other_array) end |