Jonathan Reyes
Jonathan Reyes

Reputation: 1419

Rails ActiveRecord delete record, associated records deleted one at a time

Here is an example... I have a users table that references preferences. The preferences table has a user_id. When I delete a user, I want to delete the records in the preferences table as well. However, using the belongs_to and has_many association methods in the models, I get this activity on the database:

  preference Load (0.4ms)  SELECT `preferences`.* FROM `preferences` WHERE `preferences`.`user_id` = 2
  SQL (1.3ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 2
  SQL (0.2ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 6
  SQL (0.1ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 16
  SQL (0.2ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 28
  SQL (0.2ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 34
  SQL (0.1ms)  DELETE FROM `preferences` WHERE `preferences`.`id` = 44
  userAccount Load (0.3ms)  SELECT `user_accounts`.* FROM `user_accounts` WHERE `user_accounts`.`user_id` = 2
  SQL (0.2ms)  DELETE FROM `user_accounts` WHERE `user_accounts`.`id` = 2

Is there a proper way to delete the record using perhaps DELETE FROM preferences WHERE user_id = xxxx? I'd like to do that way, because if the preferences had millions of rows, could be a lengthy query.

# User model
has_many :preferences, dependent: :destroy

# Preferences model
belongs_to :user

I could just overwrite the destroy method, but I want to see if there is a more elegant way to do this...

Upvotes: 0

Views: 1032

Answers (1)

vee
vee

Reputation: 38645

You can you the dependent: :delete_all option, instead of dependent: :destroy:

has_many :preferences, dependent: :delete_all

This will execute delete from preferences where user_id = {user_id}.

Upvotes: 1

Related Questions