:dependent => :delete_all无法正常工作

时间:2012-04-30 21:06:08

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有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

我错过了什么?

1 个答案:

答案 0 :(得分:2)

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

从指南中:

  

如果将:dependent选项设置为:destroy,则删除它   对象将调用关联对象上的destroy方法进行删除   那个对象。如果将:dependent选项设置为:delete,则   删除此对象将删除关联的对象而不调用   它的破坏方法。

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