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 中的工作方式。执行此检查的最佳方法是什么?

4

1 回答 1

0

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

def validate_image_count
    errors.add_to_base("too few") self.images.any? { |i| i.marked_for_destruction? }
end
于 2012-01-11T12:39:18.310 回答