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

时间:2012-01-11 11:59:49

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

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

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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