英文:
Eager loading with relations causes touch option not to work
问题
使用includes
来预加载Active Record时,updated_at
不会更新。
简化代码:
class MyModel < ApplicationRecord
has_many :comments,
foreign_key: 'my_model_id',
dependent: :destroy,
inverse_of: :my_model
end
class Comment < 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不会更新。
model = MyModel.find_by!(my_id: 111)
params = { "comments_attributes" => { "0" => { "id" => "2", "name" => "aaa" } }
model.update(params)
# model.updated_at会更新。
为什么在预加载时touch
选项不起作用?
英文:
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?
答案1
得分: 0
简而言之,当我们需要touch
选项在父级上正常工作时,应避免使用includes
。有关更详细的答案,请参阅此处。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论