2021年1月28日星期四

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?

https://stackoverflow.com/questions/65938886/why-does-updating-a-model-trigger-rails-to-load-other-models January 28, 2021 at 10:14PM

没有评论:

发表评论