Rails3中如何删除嵌套对象?

发布于 2024-10-25 02:57:20 字数 454 浏览 1 评论 0原文

如何删除表单中的嵌套对象?我发现我需要在父模型的accepts_nested_attributes_for 指令中添加:allow_destroy

此外,我想限制删除。如果父对象是唯一保留关联的对象,则仅应删除嵌套对象。

示例:

class Internship < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, allow_destroy => true
end

class Company < ActiveRecord::Base
  has_many :internships
end

说明:一家公司可以举办多次实习。因此,只要至少有一项其他实习与之相关,我就不想删除该公司记录。

How can I delete nested objects in a form? I found out that I need to add :allow_destroy in the parent model at the accepts_nested_attributes_for directive.

Further, I want to restrict the deletion. A nested object only should be deleted, if the parent object is the only one that retains the association.

Example:

class Internship < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, allow_destroy => true
end

class Company < ActiveRecord::Base
  has_many :internships
end

Explanation: A company can host many internships. Therefore, I do not want to delete the company record as long as there is at least one other internship associated with it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伤感在游骋 2024-11-01 02:57:20

您可以使用 dependent => :破坏

class Internship < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, allow_destroy => true
end

class Company < ActiveRecord::Base
  has_many :internships, :dependent => :destroy
end

You could use dependent => :destroy

class Internship < ActiveRecord::Base
  belongs_to :company
  accepts_nested_attributes_for :company, allow_destroy => true
end

class Company < ActiveRecord::Base
  has_many :internships, :dependent => :destroy
end
何以畏孤独 2024-11-01 02:57:20

如果您在 before_destroy 过滤器中返回 false,则销毁操作将被阻止。因此我们可以检查是否有与该公司相关的实习机会,如果有则阻止。这是在公司模型中完成的。

class Company < ActiveRecord::Base
  has_many :internships

  before_destroy :ensure_no_internships

  private

    def ensure_no_internships
      return false if self.internships.count > 0
    end

end    

If you return false in a before_destroy filter, then the destroy action will be blocked. So we can check to see if there are any internships associated to the company, and block it if so. This is done in the company model.

class Company < ActiveRecord::Base
  has_many :internships

  before_destroy :ensure_no_internships

  private

    def ensure_no_internships
      return false if self.internships.count > 0
    end

end    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文