Rails - 如何防止删除父级的所有子级记录

发布于 2024-12-26 04:20:37 字数 524 浏览 1 评论 0原文

Listing < AR
  has_many :images
  accepts_nested_attributes_for :images, :allow_destroy => true
  validate :validate_image_count

  def validate_image_count
    errors.add_to_base("too few") if images.length < 1
  end
end

Image < AR
  belongs_to :listing
end

在我的 Listing#edit 表单中,我使用 fields_for 为所有图像提供字段以及用于删除图像的复选框。这工作正常。我想强制执行一项检查,确保列表仅在至少有一个图像且最多有 6 个图像时才有效。

在我当前的设置中,我可以编辑和删除所有图像,然后更新列表。

我已尝试使用如上所示的验证,但没有被调用。可能正是nested_attributes在rails中的工作方式。执行此检查的最佳方法是什么?

Listing < AR
  has_many :images
  accepts_nested_attributes_for :images, :allow_destroy => true
  validate :validate_image_count

  def validate_image_count
    errors.add_to_base("too few") if images.length < 1
  end
end

Image < AR
  belongs_to :listing
end

In my Listing#edit form I use fields_for to provide fields for all the images along with checkboxes to delete images. This is working fine. I want to enforce a check such that a listing is valid only if it had at least one image and at most 6.

In my current setup I can go to edit and delete all the images, and then update the listing.

I have tried using a validation as shown above but thats not being called. Could be just the way nested_attributes work in rails. Whats the best way to enforce this check?

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

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

发布评论

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

评论(1

寂寞美少年 2025-01-02 04:20:37

由于当您调用验证方法时图像不会被删除,因此图像长度将返回 true。您可以使用marked_for_destruction吗?

def validate_image_count
    errors.add_to_base("too few") self.images.any? { |i| i.marked_for_destruction? }
end

as the images won't be deleted when you call the validation method it would return true on the image length. You can use marked_for_destruction?

def validate_image_count
    errors.add_to_base("too few") self.images.any? { |i| i.marked_for_destruction? }
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文