Databaas7894
Databaas7894

Reputation: 61

How to prevent multiple queries when updating a record?

I have a table customers with a couple of belong_to's: a customer belongs to a country, a sector, and a type.

I got the following result, when updating a customer:

> Customer.first.update(notes: "Some extra notes")
  Customer Load (1.4ms)  SELECT  `customers`.* FROM `customers` ORDER BY `customers`.`id` ASC LIMIT 1
  Country Load (1.5ms)  SELECT  `countries`.* FROM `countries` WHERE `countries`.`id` = '26' LIMIT 1
  Sector Load (1.6ms)  SELECT  `sectors`.* FROM `sectors` WHERE `sectors`.`id` = 89 LIMIT 1
  Type Load (1.6ms)  SELECT  `types`.* FROM `types` WHERE `types`.`id` = 8 LIMIT 1
  Customer Update (0.3ms)  UPDATE `customers` SET `notes` = "Some extra notes", `updated_at` = '2019-06-27 08:52:56' WHERE `customers`.`id` = 1

I think the extra queries are there to check if the relations are still valid. But it's extremely slow when mass updating all customers. How can I prevent those extra queries?

Upvotes: 1

Views: 199

Answers (2)

adam
adam

Reputation: 94

Your can use update_columns to skip the callbacks if you really sure you don't need it.

try

Customer.first.update_columns(notes: "Some extra notes")

Upvotes: 1

Eyeslandic
Eyeslandic

Reputation: 14890

You can use update_attribute instead, that doesn't run any validations on your model.

Customer.first.update_attribute(:notes, 'Some extra notes')

Read more about update_attribute and other nice methods

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Also note that

  • Validation is skipped.

  • Callbacks are invoked.

  • updated_at/updated_on column is updated if that column is available.

  • Updates all the attributes that are dirty in this object.

Upvotes: 2

Related Questions