ruby on rails - Limiting the number of embedded documents in Mongoid -
what correct method of limiting number of embedded documents using mongoid 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 break it:
# league 5 teams. league = league.first # copy of league. copy = league.first # create new team first instance of league , save. league.teams.build league.save # create new team second instance , save. copy.teams.build copy.save league.reload.teams.size # => 7
this case can become apparent in production multiple instances of rails app running , responding requests concurrently. need rock-solid method limit number of embedded documents. correct way this?
i ended solving using optimistic locking. there no other way definitively limit number of embedded documents.
i implemented own version of optimistic locking, here gem might useful: https://github.com/burgalon/mongoid_optimistic_locking
Comments
Post a Comment