Ruby on rails 如何删除表及其子表中的记录?

Ruby on rails 如何删除表及其子表中的记录?,ruby-on-rails,Ruby On Rails,我想创建一个链接来删除一条记录及其在外部表中的子记录。 我的模型是这样的: class Cv < ActiveRecord::Base has_many :formation end class Formation < ActiveRecord::Base belongs_to :cv validates :cv_id, presence: true end 我该怎么做? 提前感谢。如果您要向关系中添加从属关系,它也将从外键表中删除其所有关联记录 class Cv &

我想创建一个链接来删除一条记录及其在外部表中的子记录。 我的模型是这样的:

class Cv < ActiveRecord::Base
  has_many :formation
end

class Formation < ActiveRecord::Base
  belongs_to :cv
  validates :cv_id, presence: true
end
我该怎么做?
提前感谢。

如果您要向关系中添加从属关系,它也将从外键表中删除其所有关联记录

class Cv < ActiveRecord::Base
  has_many :formation, dependent: destroy
end
您需要将dependent::destroy添加到您的编队模型中,以便删除关联的记录

class Formation < ActiveRecord::Base
  belongs_to :cv, dependent: :destroy
  validates :cv_id, presence: true
end

谢谢你的帮助

<%= link_to 'delete', @cv, :data => {:confirm => 'Are you sure?'}, :method => :delete %>

外部表中的子记录?你是说相关记录吗?是的,我是说。我的队形表中有外键,你能发布你的路线吗?谢谢,但我删除的链接正确吗?那么detroy方法使用哪种呢?请
class Formation < ActiveRecord::Base
  belongs_to :cv, dependent: :destroy
  validates :cv_id, presence: true
end
<%= link_to 'delete', cvsdestroy_path(p), method: :delete %>
<%= link_to 'delete', @cv, :data => {:confirm => 'Are you sure?'}, :method => :delete %>
def destroy
    @cvdestroy = Cv.find(params[:id])
    @cvdestroy.destroy
    redirect_to cvs_path, :notice => "Your CV has been deleted"
end