我有附图中的模式
现在在答案模块中我有以下代码
class Answer < ActiveRecord::Base
belongs_to :project, class_name: "Project", foreign_key: "project_id"
belongs_to :questionair, class_name: "Questionair", foreign_key: "questionair_id"
end
这些belongs_to行是否正确?当我删除项目时,答案会按预期被删除,但在问卷调查的情况下,它无法删除相关的答案行。 我必须做些什么。我有:
class Project < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
class Questionair < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
答案 0 :(得分:1)
试试这种方式
class Answer < ActiveRecord::Base
belongs_to :project
belongs_to :questionair
end
class Project < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
class Questionair < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
要删除关联记录,您必须使用
project.destroy
如果您使用
project.delete #this does not trigger dependent destroy
答案 1 :(得分:0)
我如何理解你,你只想在单个命令中销毁所有依赖项:
project.destroy
# delete all nested answers,
# questionairies and questionairies->answers
因此,您需要在项目模型中添加一行。
class Project < ActiveRecord::Base
has_many :answers, dependent: :destroy
has_many :questionairies, dependent: :destroy
end
而不是
class Project < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
如果我理解你的错误,请更深入地解释你的问题。