【问题标题】:Rails - How to prevent deleting all children records of a parentRails - 如何防止删除父母的所有子记录
【发布时间】:2012-02-07 18:50:09
【问题描述】:
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 中的工作方式。执行此检查的最佳方法是什么?

【问题讨论】:

  • 您可以添加保存记录的代码部分吗?

标签: ruby-on-rails validation nested-forms nested-attributes fields-for


【解决方案1】:

因为当您调用验证方法时图像不会被删除,它会在图像长度上返回 true。你可以使用marked_for_destruction吗?

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

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多