mysql - rails : Delete user and user associated data in all associated models

标签 mysql sql ruby-on-rails

我是 Ruby ON Rails 新手, 我的应用有 3 个模型

class User < ActiveRecord::Base
 has_one :user_hobby
 has_one :user_interest
end

class User_hobby < ActiveRecord::Base
  belongs_to :User
 end

class User_interest < ActiveRecord::Base
  belongs_to :User

 end

我想从模型和关联数据中删除特定用户的所有记录和关联数据。

我尝试过:

@user = User.joins(:User_details,:User_record).where(user_id:'user_id')
@user.destroy

但不工作,我想不使用dependent: :destroy 仅来自 SQL

最佳答案

简单地说,在使用模型中的任何关联时使用依赖

你可以这样做:

class User < ActiveRecord::Base
 has_one :user_hobby, dependent: :destroy  # destroys the associated user_hobby
 has_one :user_interest, dependent: :destroy  # destroys the associated user_interest
end

要了解更多信息,请参阅此 link

依赖

  • 控制关联对象在其所有者被销毁时发生的情况:

  • :destroy 导致关联的对象也被销毁

  • :delete 导致关联对象直接从数据库中删除(因此回调不会执行)

  • :nullify 导致外键设置为 NULL。回调不会被执行。

  • :restrict_with_exception 如果存在关联记录,则会引发异常

  • :restrict_with_error 如果存在关联对象,则会导致向所有者添加错误

关于mysql - rails : Delete user and user associated data in all associated models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48907858/

相关文章:

jQuery html() 和换行符

单台服务器上的 MySQL 复制

php - 单击编辑时如何保留数据库驱动的下拉列表框的值?

mysql - 如何将更多变量值插入表中的单个列?

python - 以关键字作为变量的 flask sqlalchemy查询

SQL 查询(没有子查询)

ruby-on-rails - 将多个 css 类分配给 Rails 中的表元素

ruby-on-rails - Rails/Mina Gem 创建自定义任务以进行播种

php - 如何从codeigniter中的mysql表中获取所有记录

MYSQL - 无法添加外键约束 - 错误 1215