2014-12-02 24 views
0

我有一個簡歷模型has_many:技能,我的技能模型belongs_to:簡歷。爲什麼我的嵌套屬性與父項一起被銷燬?

我在簡歷表格中嵌套技能表單,它創造了完美的記錄和關係。但是當我試圖摧毀簡歷時,相關的技能不會隨着它被破壞。

這裏是我的模型:

# Resume.rb 

class Resume < ActiveRecord::Base 
    has_many :skills 

    belongs_to :user 

    accepts_nested_attributes_for :skills, allow_destroy: true 
end 


# Skill.rb 

class Skill < ActiveRecord::Base 
    belongs_to :resume 
end 

這裏是在resume_controller.rb

def resume_params 
    params.require(:resume).permit(:user_id, :title, :summary, :job_title, skills_attributes [:skill_name, :_destroy]) 
end 

強PARAMS至於我可以告訴我傳遞_destroy鍵正常。我注意到有些人在表單中有_destroy複選框。當我摧毀整個簡歷時,我希望刪除這些技能。謝謝!

回答

2

您所指定的全部內容是,您可以像使用您在某些示例中提到的複選框一樣,摧毀簡歷上的技能。如果您希望它破壞與簡歷銷燬有關的所有技能,您可以調整您的has_many聲明。

has_many :skills, dependent: :destroy 
2

Resume模型添加:dependent => :destroy象下面這樣:

class Resume < ActiveRecord::Base 
    has_many :skills, :dependent => :destroy 

    belongs_to :user 

    accepts_nested_attributes_for :skills, allow_destroy: true 
end 

:dependent控制時,他們的主人被破壞會發生什麼變化相關對象:

  • :destroy導致所有相關的對象也被銷燬

  • :delete_all導致所有相關的對象直接從數據庫中刪除(因此回調將不會執行)

  • :nullify導致外鍵設置爲NULL 。回調不執行。

  • :restrict_with_exception引起,如果有任何相關記錄

  • :restrict_with_error引起,如果有任何關聯的對象

+1

這是完美的被添加到車主錯誤時引發異常,謝謝您! – zhs 2014-12-02 05:23:09

相關問題