【问题标题】:Why aren't my nested attributes being destroyed along with the parent?为什么我的嵌套属性没有与父级一起被破坏?
【发布时间】:2014-12-02 05:08:52
【问题描述】:

我有一个拥有_many :skills 的简历模型,以及我的属于_to :resume 的技能模型。

我将技能表格嵌套在简历表格中,它完美地创建了记录和关系。但是当我试图破坏简历时,相关的技能并没有随之被破坏。

这是我的模型:

# 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

据我所知,我正确地传递了 _destroy 密钥。我注意到有些人在表单中有 _destroy 复选框。我希望在销毁整个简历时删除技能。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    您所指定的只是您可以破坏简历上的技能,就像您在某些示例中提到的复选框一样。如果您希望它在销毁简历时销毁所有相关技能,您可以调整您的 has_many 声明。

    has_many :skills, dependent: :destroy
    

    【讨论】:

      【解决方案2】:

      在您的Resume 模型中添加:dependent =&gt; :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 如果有任何关联对象,则会将错误添加到所有者

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多