Mongoid保存文档,尽管自定义验证无效

时间:2012-09-30 16:17:52

标签: ruby-on-rails ruby validation associations mongoid

我不确定这是Mongoid或标准Rails验证器的问题,但是无效的文档仍然保存到数据库中。

我的模型设置为:

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个团队使用build而不是create league.teams << FactoryGirl.build(:team),那么测试就会通过。然而,这不是一个解决方案,因为我想保证联盟不能拥有超过12支球队,无论所添加的球队是新的还是已经在数据库中。

无论如何都要保证这个吗?

修改

如下所示,在Team模型中添加验证器似乎也不起作用。

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是原子操作的事实有关,因此它们会跳过回调和验证。话虽这么说,这必须是一个相当普遍的用例,不是吗?那么其他人如何验证被引用文档的数量呢?

1 个答案:

答案 0 :(得分:0)

我不认为问题出在<<push方法上,因为它们都应该触发模型的验证。

尝试使用:

league.teams << FactoryGirl.create(:team, league: league)