使用带有 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 应用程序的多个实例同时运行并响应请求。我需要一种坚如磐石的方法来限制嵌入文档的数量。这样做的正确方法是什么?