Rails accepted_nested_attributes计数验证

Ell*_*iot 4 activerecord ruby-on-rails activemodel ruby-on-rails-3

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

销售模式:

class Sale < ActiveRecord::Base
   has_many :items, :dependent => :destroy
   has_many :images, :through => :items

   accepts_nested_attributes_for :items, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)

物品型号:

class Item < ActiveRecord::Base

  belongs_to :sale, :dependent => :destroy
  has_many :images, :dependent => :destroy

  accepts_nested_attributes_for :images

end
Run Code Online (Sandbox Code Playgroud)

图像型号:

class Image < ActiveRecord::Base
  belongs_to :item, :dependent => :destroy
end
Run Code Online (Sandbox Code Playgroud)

dig*_*ter 6

创建用于验证的自定义方法

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

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
Run Code Online (Sandbox Code Playgroud)

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

  • 理想情况下,将这些方法命名为validate_item_count和validate_image_count,因为这可以明确您的意图并且方法会添加错误. (2认同)