chief
chief

Reputation: 301

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?

Upvotes: 29

Views: 19066

Answers (4)

Edward
Edward

Reputation: 141

ActiveRecord::Base.transaction do
  ActiveRecord::Base.connection.execute('LOCK TABLE pictures IN EXCLUSIVE MODE')
  if (@album.pictures.count < 10) 
    @album.pictures.create()
  end
end

I believe this is the most correct solution. It guards against concurrency issues/race conditions.

Upvotes: 0

jstejada
jstejada

Reputation: 872

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

Upvotes: 48

hurikhan77
hurikhan77

Reputation: 5931

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

Upvotes: 29

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54742

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

Upvotes: 9

Related Questions