Mongoid:限制嵌入对象的数量

发布于 2024-11-05 06:57:11 字数 523 浏览 1 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沧桑㈠ 2024-11-12 06:57:11

Mongoid 包含 ActiveModel::Validations,因此您应该能够使用该模块中包含的方法:

class Album
  include Mongoid::Document
  embeds_many :photos

  validate :less_than_fifty_photos

  def less_than_fifty_photos
    errors.add(:base, "Too many photos") if self.photos.count >= 50
  end
end

更多信息: http:// /mongoid.org/docs/validation.html

Mongoid includes ActiveModel::Validations, so you should be able to use the methods contained in that module:

class Album
  include Mongoid::Document
  embeds_many :photos

  validate :less_than_fifty_photos

  def less_than_fifty_photos
    errors.add(:base, "Too many photos") if self.photos.count >= 50
  end
end

More info: http://mongoid.org/docs/validation.html

堇年纸鸢 2024-11-12 06:57:11

您还可以使用 validates_length_of 并且它应该可以工作。

You can also use validates_length_of and it should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文