2012-03-29 24 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 

你只需要爲默認的郵件中提到的字符數,以提供自己的信息。