I am using Mongoid with Rails 3. What would be the best way to limit the number of embedded objects (photos) that can be stored within each parent object (album)?
class Album
include Mongoid::Document
embeds_many :photos
end
class Photo
include Mongoid::Document
embedded_in :album, :inverse_of => :photos
end
With ActiveRecord, I would do something like:
has_many :photos, :before_add => :enforce_photo_limit
private
def enforce_photo_limit
raise "Too many photos" if self.photos.count >= 50
end
…but this isn’t supported by Mongoid.
Any suggestions much appreciated.
Thanks.
Mongoid includes ActiveModel::Validations, so you should be able to use the methods contained in that module:
More info: http://mongoid.org/docs/validation.html