0

我有 2 个具有 1 对多关联的模型,我试图让 Rails 级联删除工作。

我对rails很陌生,我已经尝试了所有我能做的事情,但我仍然无法让它工作......

这是我的 2 个模型

class CmsHomeSlide < ActiveRecord::Base
    attr_accessible :slide_order, :start_datetime, :end_datetime, :slide_type, :header, :headline, :cta_text, :cta_link, :active
    has_many :cms_home_slide_detail, :dependent => :delete_all
    validates_presence_of :slide_type, :slide_order
end

class CmsHomeSlideDetail < ActiveRecord::Base
    attr_accessible :start_datetime, :end_datetime, :position, :image_url, :link, :cms_home_slide, :active
    belongs_to :cms_home_slide
end

以及我正在使用的测试脚本(作为跑步者,但开发环境和测试环境以同样的方式失败)

CmsHomeSlide.delete_all
CmsHomeSlideDetail.delete_all

slide = Factory(:home_slide)
det1 = Factory(:home_slide_detail, :cms_home_slide => slide, :position => 1)
det2 = Factory(:home_slide_detail, :cms_home_slide => slide, :position => 2)

puts "Slides length #{CmsHomeSlide.all.length}"
puts "Details length #{CmsHomeSlideDetail.all.length}"

slide.delete

puts "Slides length #{CmsHomeSlide.all.length}"
puts "Details length #{CmsHomeSlideDetail.all.length}"

输出是

Slides length 1
Details length 2
Slides length 0
Details length 2

我错过了什么?

4

1 回答 1

2

您需要使用:dependent => :delete:dependent => :destroy

从指南:

如果将 :dependent 选项设置为 :destroy,则删除此对象将调用关联对象的 destroy 方法以删除该对象。如果将 :dependent 选项设置为 :delete,则删除此对象将删除关联的对象,而无需调用其 destroy 方法。

http://guides.rubyonrails.org/association_basics.html

于 2012-04-30T21:11:17.273 回答