2012-03-29 86 views
4

我有三个模型。销售,物品和图像。我想验证,创建销售时,每个销售和一个或多个项目至少有三张照片。什么是实现这一目标的最佳方式?Rails的accept_nested_attributes计数验证

销售模式:

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 

产品型号:

class Item < ActiveRecord::Base 

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

    accepts_nested_attributes_for :images 

end 

图片型号:

class Image < ActiveRecord::Base 
    belongs_to :item, :dependent => :destroy 
end 

回答

6

用于验证

在你的销售模型添加someth创建自定义方法荷兰国际集团这样的:

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 

希望这有助于在所有,好运和快乐编码。

+2

理想地命名这些方法validate_item_count和validate_image_count,因为这会澄清您的意图以及方法是否会添加错误。 – joelparkerhenderson 2012-03-29 21:17:41

+0

好点,谢谢你的加入。 – digicazter 2012-03-29 21:27:11

2

另一个选择是使用这个小技巧与length验证。虽然大多数例子表明它正在与文本中,它会检查协会的长度,以及:

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 

你只需要为默认的邮件中提到的字符数,以提供自己的信息。