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
在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于当您调用验证方法时图像不会被删除,因此图像长度将返回 true。您可以使用marked_for_destruction吗?
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?