我不確定這是否是Mongoid或標準Rails驗證程序的問題,但是無效的文檔仍將保存到數據庫。儘管自定義驗證無效,但Mongoid保存文檔
我有模型設置爲一樣的東西:
class League
include Mongoid::Document
has_many :teams
validate do
if teams.size > 12
errors.add(:teams, 'too many teams')
end
end
end
class Team
include Mongoid::Document
belongs_to :league
end
我希望下面的測試通過,但事實並非如此。除了我的自定義驗證,無法將超過12個球隊添加到聯盟中,無論如何聯盟都可以得到13支球隊的保存。
# Factory for a League.
FactoryGirl.define do
factory :league do
name "Test League"
factory :league_with_teams do
ignore do
teams_count 5
end
after(:create) do |league, evaluator|
FactoryGirl.create_list(:team,
evaluator.teams_count,
league: league)
end
end
end
describe League do
it "should not allow more than 12 teams" do
league = FactoryGirl.create(:league_with_teams, teams_count: 12)
league.teams << FactoryGirl.create(:team)
league.should_not be_valid # passes
League.find(league.id).teams.size.should eq(12) # fails
end
end
有趣的是,如果我改變線路中增加了第13組使用的構建,而不是創造,league.teams << FactoryGirl.build(:team)
測試,然後將測試通過。然而,這不是一個解決方案,因爲我想保證聯盟不能超過12支球隊,無論球隊是否新增或已經在數據庫中。
反正有保證嗎?
編輯
添加一個驗證的團隊模式,像我一樣下面,似乎沒有任何工作。
class Team
include Mongoid::Document
belongs_to :league
validate do |team|
if league.teams.size > 12
errors.add :base, "cannot have more than 12 teams in a league"
end
end
end
我相信問題是與事實是<<
和push
是原子操作的事,因此,他們跳過回調和驗證。話雖如此,這肯定是一個相當常見的用例,不是嗎?那麼其他人如何驗證被引用文檔的數量呢?
驗證應該是在球隊 – apneadiving
似乎這不是解決問題。 – Marcus
你究竟做了什麼? – apneadiving