验证关联对象的数量

时间:2009-09-14 14:01:25

标签: ruby-on-rails validation

鉴于此:

class User < ActiveRecord::Base
  has_many :photos
  MAX_PHOTOS = 5
  validate :quantity_of_photos

  def quantity_of_photos
    ???
  end
end

而且:

@user.photos.size  # => 5

我需要这个失败:

@user.photos << Photo.create(valid_photo_attributes)

我该如何进行验证?

1 个答案:

答案 0 :(得分:1)

将照片数量方法移动到照片模型:

class Photo < ActiveRecord::Base

   belongs_to :user
   validates :quantity_of_photos

    def quantity_of_photos
      if new_record? && user.photos.size >= User::MAX_PHOTOS
        errors.add_to_base "You cannot have more than #{MAX_PHOTOS} photos."
      end
    end

end

ActiveRecord实例的有效性取决于它的错误数组中是否存在错误。