0

使用带有 Rails 的 Mongoid 限制嵌入文档数量的正确方法是什么。

我试过这个:

class League
  include Mongoid::Document

  embeds_many :teams
  validate :validate_teams

  def validate_teams
    if teams.size > 6
      errors.add(:base, "too many teams")
    end
    if !errors.empty?
      raise Mongoid::Errors::Validations.new(self)
    end
  end

end

但这会破坏它:

# Get a league with 5 teams.
league = League.first

# Get a copy of the league.
copy = League.first

# Create a new team for the first instance of the league and save.
league.teams.build
league.save

# Create a new team for the second instance and save.
copy.teams.build
copy.save

league.reload.teams.size # => 7

这种情况在生产中会变得很明显,因为 Rails 应用程序的多个实例同时运行并响应请求。我需要一种坚如磐石的方法来限制嵌入文档的数量。这样做的正确方法是什么?

4

1 回答 1

1

我最终通过使用乐观锁定解决了这个问题。没有其他方法可以明确限制嵌入文档的数量。

我实现了自己的乐观锁定版本,但这里有一个可能有用的 gem:https ://github.com/burgalon/mongoid_optimistic_locking

于 2013-08-02T21:50:38.850 回答