Mongoid:限制嵌入对象的数量
我正在使用 Mongoid 和 Rails 3。限制每个父对象(相册)中可以存储的嵌入对象(照片)数量的最佳方法是什么?
class Album
include Mongoid::Document
embeds_many :photos
end
class Photo
include Mongoid::Document
embedded_in :album, :inverse_of => :photos
end
对于 ActiveRecord,我会做类似的事情:
has_many :photos, :before_add => :enforce_photo_limit
private
def enforce_photo_limit
raise "Too many photos" if self.photos.count >= 50
end
...但这不受 Mongoid 支持。
任何建议都非常感激。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Mongoid 包含 ActiveModel::Validations,因此您应该能够使用该模块中包含的方法:
更多信息: http:// /mongoid.org/docs/validation.html
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
您还可以使用 validates_length_of 并且它应该可以工作。
You can also use validates_length_of and it should work.