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 

在我的清单#编辑表单中,我使用fields_for为所有图像提供了字段,并提供了用于删除图像的复选框。这工作正常。我想强制执行一项检查,以使列表仅在至少有一个图像且最多为6时有效。Rais - 如何防止删除家长的所有子女记录

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

我已经尝试使用上面显示的验证,但那不被称为。可能只是nested_attributes在rails中工作的方式。什么是执行此检查的最佳方式?

+0

您可以添加保存记录的代码部分吗? – zsquare 2012-01-11 12:24:37

回答

0

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

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

感谢您的回答! – robodisco 2012-01-22 12:45:57

+0

不客气。 :) – 2012-01-26 13:38:31