I have an album which has_many photos. A counter_cache setup updates the photos_count column in the album table. How do I limit the number of photos for an album?
A:
How about adding a custom validation method to the Photo model?
LIMIT = 50
validate_on_create do |record|
record.validate_quota
end
def validate_quota
return unless self.album
if self.album.photos(:reload).count >= LIMIT
errors.add(:base, :exceeded_quota)
end
end
Marcel J.
2010-02-14 23:26:48
A:
Use a validation hook:
class Album
has_many :photos
validate_on_create :photos_count_within_bounds
private
def photos_count_within_bounds
return if photos.blank?
errors.add("Too many photos") if photos.length > 10
end
end
class Photo
belongs_to :album
validates_associated :album
end
hurikhan77
2010-02-14 23:27:29
Thanks for the advice guys. I have got Marcel's code working.
chief
2010-02-15 00:17:27