使用关联进行急加载会导致touch选项不起作用。

huangapple go评论65阅读模式
英文:

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 &lt; ApplicationRecord
  has_many :comments,
           foreign_key: &#39;my_model_id&#39;,
           dependent: :destroy,
           inverse_of: :my_model

end

class Comments &lt; 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 = {&quot;comments_attributes&quot;=&gt;{&quot;0&quot;=&gt;{&quot;id&quot;=&gt;&quot;2&quot;, &quot;name&quot;=&gt;&quot;aaa&quot;}}
model.update(params)
# model.updated_at DOES NOT get updated.
model = MyModel.find_by!(my_id: 111)
params = {&quot;comments_attributes&quot;=&gt;{&quot;0&quot;=&gt;{&quot;id&quot;=&gt;&quot;2&quot;, &quot;name&quot;=&gt;&quot;aaa&quot;}}
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.

huangapple
  • 本文由 发表于 2023年2月16日 11:27:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定