Rails accepted_nested_attributes计数validation

我有三个型号。 销售,物品和图像。 我想validation,在创建促销时,每次促销至少有三张照片和一件或多件商品。 实现这一目标的最佳方法是什么?

销售模式:

class Sale  :destroy has_many :images, :through => :items accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true end 

物品型号:

 class Item  :destroy has_many :images, :dependent => :destroy accepts_nested_attributes_for :images end 

图像型号:

 class Image  :destroy end 

创建用于validation的自定义方法

在您的销售模型中添加如下内容:

 validate :validate_item_count, :validate_image_count def validate_item_count if self.items.size < 1 errors.add(:items, "Need 1 or more items") end end def validate_image_count if self.items.images.size < 3 errors.add(:images, "Need at least 3 images") end end 

希望这会有所帮助,祝你好运和编码愉快。

另一种选择是使用这个小技巧进行lengthvalidation。 虽然大多数示例都显示它与文本一起使用,但它也会检查关联的长度:

 class Sale < ActiveRecord::Base has_many :items, dependent: :destroy has_many :images, through: :items validates :items, length: { minimum: 1, too_short: "%{count} item minimum" } validates :images, length: { minimum: 3, too_short: "%{count} image minimum" } end 

您只需提供自己的消息,因为默认消息提到了字符数。