我有以下情况:
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
nutrient.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_nutrients
,dependent: :destroy
无效。删除用户后,这些条目就在那里。
我在这里缺少什么?
答案 0 :(得分:0)
根据这篇文章 - 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
和营养素.rb
has_many :user_nutrients
has_many :users, through: :user_nutrients, dependent: :destroy