簡體   English   中英

Ruby on Rails:刪除相關模型的更好方法

[英]Ruby on Rails: Better approach to delete related models

我定義了以下類/關系:

class Component < ActiveRecord::Base
    has_many :component_stories,:dependent => :destroy
    has_many :stories, :through => :component_stories
end

class Story < ActiveRecord:Base
    has_many :component_stories,:dependent => :destroy
    has_many :components, :through => :component_stories
end

class ComponentStory < ActiveRecord::Base
    belongs_to :component
    belongs_to :story
end

假設我們的component1包含2個故事:story1和story2。 story2也屬於component2。 如果我們刪除component1,則story1將被永久刪除,但story2仍將保留,因為它屬於component2。 我在Component模型中定義了一個方法來刪除與任何其他組件無關的故事:

def delete_dependent_stories
   stories.each do |story|
     if story.component_stories.size == 1
       story.destroy
     end
   end
end

該方法將在components_controller的destroy操作中調用:

def destroy
   component = Component.find(params[:id])
   component.delete_dependent_stories
   component.destroy
   ...
end

這樣,我確保沒有與任何組件無關的“僵屍”故事。 我擔心的是,是否有一種更好的方法可以代替Component模型中的該方法。

您應該利用這樣的模型回調:

class Component < ActiveRecord::Base
  has_many :component_stories,:dependent => :destroy
  has_many :stories, :through => :component_stories

  after_destroy :delete_dependent_story?

  private

  def delete_dependent_stories
    stories.each do |story|
      if story.has_component_stories?
        story.destroy
      end
  end
end

class Story < ActiveRecord:Base
  has_many :component_stories,:dependent => :destroy
  has_many :components, :through => :component_stories

  self.has_component_story?
    component_stories.size == 1
  end
end

不要使用before_destroy因為它會刪除story無論component刪除成功與否。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM