Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

activerecord - Why does updating a model trigger rails to load other models?

I've got a weird behavior on my project. If I update/save a record on my ::Product model, rails always load up other models relates to it.

this:

p = Product.first
p.update(name: 'whatever')

will output this:

 (1.2ms)  BEGIN
  Product::Brand Load (2.6ms)  SELECT  `product_brands`.* FROM `product_brands` WHERE `product_brands`.`id` = 24 LIMIT 1
  Product::Condition Load (5.4ms)  SELECT  `product_conditions`.* FROM `product_conditions` WHERE `product_conditions`.`id` = 3 LIMIT 1
  Product::Category Load (1.3ms)  SELECT  `product_categories`.* FROM `product_categories` WHERE `product_categories`.`id` = 2 LIMIT 1
  Product Update (4.0ms)  UPDATE `products` SET `updated_at` = '2021-01-28 21:10:16', `name` = 'whatever' WHERE `products`.`id` = 1
   (0.5ms)  COMMIT

product belongs to :brand, :condition, and :category, but it also belongs to other models as well, but only these three models got triggered.

Any idea why this happened?

EDIT I didn't set any custom validation in the Product class. Nor does scope or default_scope.

EDIT 2 I just realised something. It doesn't only happen in my Product model. But ALL models that have belongs_to :something relationship will trigger the same queries, unless I add optional: true. Is it an intended behavior for Rails? Can I prevent this without adding optional: true to the belongs_to relation?

question from:https://stackoverflow.com/questions/65938886/why-does-updating-a-model-trigger-rails-to-load-other-models

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can you post the code from the Product model? Validations, scopes, callbacks, basically everything except methods. Most probably you have something that causes the eager loading there. The most obvious would be:

has_many :brands, :include => true

include :brands

default_scope includes(:brands)

Also as Sergio pointed out, many callbacks and validations can load these related models to perform some actions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...