employee1.department # => nil
department1.employees << employee1 # triggers DB save
employee1.department # => department1
Adding a model to a has_many
relationship with <<
updates that models inverse belongs_to
relationship in-memory. We didn’t need to reload employee1 or reset it’s association to see it’s #department
, it was magically set in-memory to the right thing.
However, the inverse operation of removing a model from a has_many
relationship does not behave similarly.
employee1.department # => department1
department1.delete(employee1)
employee1.department # => department1, wrong in memory!
employee1.reload
employee1.department # => nil, after re-fetch from db
This seems inconsistent. Should it be updating the inverse in-memory here too? Why one and not the other?
Is there any other way I can do this operation, that will save to the DB, and update both objects in-memory, without requiring me to reset the association and trigger another separate DB query?