【问题标题】:dependent: :destroy not working依赖: :destroy 不工作
【发布时间】:2016-06-06 19:50:19
【问题描述】:

我有以下情况:

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :create_profile
  after_create :programstart

  has_one :profile, dependent: :destroy
  has_many :weights, dependent: :destroy
  has_many :programstarts, dependent: :destroy

  has_many :user_nutrients, dependent: :destroy
  has_many :nutrients, through: :user_nutrients, dependent: :destroy


  private

  def programstart
    Programstart.create(:user_id => id)
  end
end

营养素.rb

class Nutrient < ActiveRecord::Base
  validates :name, uniqueness: true

  has_many :user_nutrients
  has_many :users, through: :user_nutrients
end

user_nutrient.rb

class UserNutrient < ActiveRecord::Base
  belongs_to :user 
  belongs_to :nutrient
end

对于配置文件、权重和程序启动,dependent: :destroy 有效。当我删除用户时,所有关联的数据库条目都会被删除。但是,对于user_nutrientsdependent: :destroy 不起作用。删除用户后,这些条目仍然存在。

我在这里错过了什么?

【问题讨论】:

  • 错误信息是什么?
  • 没有错误信息。我从控制台中删除了用户,所有依赖记录都被删除,除了 user_nutrients 表中的记录。

标签: ruby-on-rails associations


【解决方案1】:

根据这篇文章 - http://makandracards.com/makandra/32175-don-t-forget-automatically-remove-join-records-on-has_many-through-associations 您应该执行以下操作:

has_many :user_nutrients
has_many :nutrients, through: :user_nutrients, dependent: :destroy

在 nut.rb 中

has_many :user_nutrients
has_many :users, through: :user_nutrients, dependent: :destroy

【讨论】:

  • 试过了 - 记录还在。
猜你喜欢
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多