mysql - Rails ActiveRecord 删除记录,一次删除一条关联记录

标签 mysql ruby-on-rails

这是一个示例...我有一个引用首选项的用户表。首选项表有一个 user_id。当我删除用户时,我想同时删除首选项表中的记录。但是,在模型中使用 belongs_tohas_many 关联方法,我在数据库上获得了此事件:

  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

是否有正确的方法可以使用从首选项中删除WHERE user_id = xxxx来删除记录?我想这样做,因为如果首选项有数百万行,可能是一个很长的查询。

# User model
has_many :preferences, dependent: :destroy

# Preferences model
belongs_to :user

我可以覆盖 destroy 方法,但我想看看是否有更优雅的方法来做到这一点......

最佳答案

你可以dependent: :delete_all选项,而不是dependent: :destroy:

has_many :preferences, dependent: :delete_all

这将执行从 user_id = {user_id} 的首选项中删除

关于mysql - Rails ActiveRecord 删除记录,一次删除一条关联记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23065384/

相关文章:

ruby-on-rails - `initialize' : getaddrinfo: Temporary failure in name resolution (SocketError)

javascript - skip_before_filter :authenticate_user! 不适用于 AJAX 调用

Java - 无法从 MySQL StoredProcedure 返回/访问结果集

mysql - 优化的SQL查询

php - 比较 MySQL 和 PHP 之间的数据类型

mysql - 我的 MySQL 脚本语法错误

mysql - HTTP 状态 500 - 在第 50 行处理 JSP 页面/ratinglist.jsp 时发生异常

ruby-on-rails - Rails 4 : Undefined method `total_price' for nil:NilClass, 订单 Controller

ruby-on-rails - 1 个 View 中来自单独 Controller 的 2 个表单

ruby-on-rails - Rails 迁移和 PostgreSQL : separate user for migration and setting privileges for production user