Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of objects in has_many association

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?

like image 553
chief Avatar asked Feb 14 '10 23:02

chief


2 Answers

In my case, it was sufficient to use validates_length_of:

class Album
  has_many :photos
  validates_length_of :photos, maximum: 10
end

class Photo
  belongs_to :album
  validates_associated :album
end
like image 134
jstejada Avatar answered Nov 14 '22 22:11

jstejada


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.size > 10
  end
end

class Photo
  belongs_to :album
  validates_associated :album
end
like image 29
hurikhan77 Avatar answered Nov 14 '22 23:11

hurikhan77