Q:

Limiting the number of embedded documents in Mongoid

What is the correct method of limiting the number of embedded documents using Mongoid with Rails.
I've tried this:
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

But this will break it:
# 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

This case can become apparent in production with multiple instances of the Rails app running and responding to requests concurrently. I need a rock-solid method to limit the number of embedded documents. What is the correct way to do this?

A:

I ultimately ended up solving this by using optimistic locking. There is no other way to definitively limit the number of embedded documents.
I implemented my own version of optimistic locking, but here is a gem that might be useful: https://github.com/burgalon/mongoid_optimistic_locking

