Mar*_*cus 5 ruby validation ruby-on-rails 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为原子操作,因此,他们跳过回调和验证.话虽这么说,这必须是一个相当普遍的用例,不是吗?那么其他人如何验证被引用的文档数量呢?
小智 0
我认为问题不在于<<或push方法,因为它们都应该触发模型的验证。
尝试使用:
league.teams << FactoryGirl.create(:team, league: league)
| 归档时间: | 
 | 
| 查看次数: | 1036 次 | 
| 最近记录: |