通过FactoryGirlvalidation错误

我在通过FactoryGirlvalidation我的数据时遇到问题。

对于team.rb,自定义validation为has_only_one_leader和belongs_to_same_department

class Team  { where(active: true) } validate :has_only_one_leader validate :belongs_to_same_department def has_only_one_leader unless self.users.where!(designation: "Team Leader").size == 1 errors.add(:team, "needs to have exactly one leader") end end def belongs_to_same_department unless self.users.where!.not(department: self.department).size == 0 errors.add(:users, "should belong to the same department") end end 

我还将包括membership.rb和user.rb(仅限关联)仅供参考。

 class Membership < ActiveRecord::Base belongs_to :team belongs_to :user end class User < ActiveRecord::Base has_many :memberships has_many :teams, through: :memberships end 

这是team.rb的工厂

 FactoryGirl.define do factory :team do sequence(:name) {|n| "Team #{n}" } department "Architectural" before(:create) do |team| team.users << FactoryGirl.create(:user, designation: "Team Leader", department: "Architectural") team.users << FactoryGirl.create_list(:user, 5, designation: "CAD Operator", department: "Architectural") end end end 

似乎在我在rails控制台中执行FactoryGirl.create(:team)之后,似乎我从validation中收到了错误消息。

当我手动建立一个团队时,我注意到了两件事,特别是向团队中添加了1名领导者和5名属于同一部门的成员:

  1. team.users.where!(designation: "Team Leader").size返回6虽然只有一个领导者,同样可以将指定更改为CAD操作员,但返回6尽管团队中只有五个非领导者。

  2. 同样可以检查成员是否在同一个部门, team.users.where!.not(department: team.department).size返回6 ,尽管它们都属于同一个部门。

在我的模型或工厂中是否有任何修改?

以下是我在得到答案之前发现的事情。

  1. team.users.where(designation: "Team Leader")返回User::ActiveRelation_AssociationRelation对象
  2. team.users返回User::ActiveRecord_Associations_CollectionProxy对象
  3. CollectionProxy没有方法where因为这个方法(在我看来)是对数据库的查询(除非团队已经保存在数据库中,你可以使用where ,但在这种情况下,它只用于构建)

因此,我使用了带有countselect方法,返回正确的值。 我将用问题中的例子来说明答案。

  1. team.users.select(:designation) {|user| user.designation == "Team Leader"}.count team.users.select(:designation) {|user| user.designation == "Team Leader"}.count返回1
  2. team.users.select(:department) {|user| user.department != team.department}.count team.users.select(:department) {|user| user.department != team.department}.count返回0