回答

3

S0我假設一個職位has_many圖像。

你可以嘗試驗證的保存,像下面的圖像的數量(此代碼沒有經過測試!):

class Post 
    has_many :images 
    validate_on_create :images_limit 

    private 

    def images_limit 
    return if images.blank? 
    errors.add("You have reached the image limit") if images.length > 10 
    end 
end 

class Image 
    belongs_to :post 
    validates_associated :post 
end 
+0

真的太好了!我只需要通過 - > validate:images_limit,:on =>:create來替換validates_on_create。我仍然有問題,當顯示錯誤信息時,我有很多字段作爲我嘗試發送的圖像。如果我附上15張照片,我會有15個文件,第一個(如此16)。在我的控制器中添加:@ post.photos.build顯示我的表單的字段=><%= f.fields_for:images do | images | %><%= image.file_field:image ...等等。你有什麼想法嗎?無論如何,你的代碼正在驗證!謝謝! – Dl33ter

+0

我忘了,我不得不改變errors.add(「message」)bu errors.add(:images,「message)。以防萬一別人需要它。 – Dl33ter

+0

很高興幫助 - 標記答案,如果你認爲它會對其他人有用:) – dtt101