1

验证 rails 3.2 中创建的 has_many 对象的数量?

我需要对关联对象的“最大/最小”计数进行自定义验证。我有房地产,有

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
4

2 回答 2

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

查看文档以获取更多详细信息。

于 2013-05-08T09:14:20.823 回答
3

不确定我是否完全理解,但是如果您尝试限制给定不动产的 realty_images 的数量,并假设 realty.maximum 包含该给定不动产的最大限制:

在 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
于 2013-05-08T06:42:42.923 回答