2013-05-08 41 views
1

驗證rails 3.2中創建的has_many對象的數量?驗證rails中創建的has_many對象的數量3.2

我需要一個自定義驗證關聯對象的「最大/最小」計數。 我有房產,有

has_many :realty_images, :dependent => :destroy 
accepts_nested_attributes_for :realty_images 

和realty_image:

class RealtyImage < ActiveRecord::Base 
    attr_accessible :avatar, :image, :realty_id 
    belongs_to :realty 

    #here a suppose I need to put some kind of custom validation 
    mount_uploader :image, ImageUploader 
end 

回答

5

該標準的檢驗方法與協會工作得很好:

class Ad 
    has_many :realty_images 

    # make sure there are some images 
    validates_presence_of :realty_images 

    # or make sure the number of images is in certain range 
    validates_length_of :realty_images, within: 5..10 
end 

退房documentation瞭解更多詳情。

+0

非常感謝。我不知道這樣的存在。這很有用。 – 2013-05-08 09:25:48

+0

** @ Semyon Perepelitsa **你能告訴我爲什麼會發生這種情況[鏈接](http://stackoverflow.com/questions/16413271/nester-attributes-for-has-many-are-not-shown-if - 表單驗證失敗?) – 2013-05-08 09:45:25

+0

當然,我也回答了。我希望它有幫助。 – 2013-05-08 10:11:21

3

不知道如果我完全理解,但如果你試圖限制特定不動產realty_images的數量,並假設房地產。最大包含給定的不動產最大限制:

在RealtyImage型號:

class RealtyImage < ActiveRecord::Base 
    attr_accessible :avatar, :image, :realty_id 
    belongs_to :realty 

    validate :maximum_number_of_realty_images 
    mount_uploader :image, ImageUploader 

    protected 
    def maximum_number_of_realty_images 
    errors.add(:base, "Maximum reached") unless realty.realty_images.count < realty.maximum 
    end 
end 
+0

謝謝你的回答,你能告訴我更多的事情,我不確定,它「驗證」或「驗證」??。和:base這意味着錯誤將作爲基礎彈出請注意<或特定字段 – 2013-05-08 07:42:18

+0

@AndreyYasinishyn對於註冊自定義驗證器'驗證',對於預定義的Rails'驗證'。關於錯誤,因爲它被添加到「基礎」中,所以與整個模型連接,而不是針對特定的屬性;所以你可以檢查它realty_image.errors – Galen 2013-05-08 07:52:39

+0

我使用這種方法發生錯誤:realty_image.rb:4:語法錯誤,意外的'(',期待keyword_end 驗證:maximum_number_of_realty_images(10) – 2013-05-08 08:42:33