When using includes
to eager load an active record, the updated_at does not get updated.
Simplified code:
class MyModel < ApplicationRecord
has_many :comments,
foreign_key: 'my_model_id',
dependent: :destroy,
inverse_of: :my_model
end
class Comments < ApplicationRecord
belongs_to :my_model, foreign_key: :my_model_id,
inverse_of: :comments,
touch: true
end
model = MyModel.includes(comments: :user).find_by!(my_id: 111)
params = {"comments_attributes"=>{"0"=>{"id"=>"2", "name"=>"aaa"}}
model.update(params)
# model.updated_at DOES NOT get updated.
model = MyModel.find_by!(my_id: 111)
params = {"comments_attributes"=>{"0"=>{"id"=>"2", "name"=>"aaa"}}
model.update(params)
# model.updated_at DOES get updated.
Why would the touch
option not work when eager loading?
In short, we should avoid includes
when we need the touch option to work correctly on the parent. See here for a more detailed answer.