通过FactoryGirl验证错误

时间:2014-07-05 04:08:28

标签: ruby-on-rails ruby validation factory-bot

我在通过FactoryGirl验证数据时遇到问题。

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

class Team < ActiveRecord::Base
    attr_accessible :name, :department, :active

    has_many :memberships
    has_many :users, through: :memberships

    accepts_nested_attributes_for :memberships, :users

    validates :department, inclusion: [nil, "Architectural", "Interior Design"]
    validates_uniqueness_of :name, scope: :department, conditions: -> { 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)后,似乎我从验证中收到了错误消息。

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

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

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

  3. 我的模型或工厂是否有任何修改?

1 个答案:

答案 0 :(得分:0)

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

  1. team.users.where(designation: "Team Leader")会返回User::ActiveRelation_AssociationRelation个对象
  2. team.users会返回User::ActiveRecord_Associations_CollectionProxy个对象
  3. CollectionProxy没有方法where,因为此方法(在我看来)是对数据库的查询(除非团队已保存在数据库中,否则您可以使用{{1}但是在这种情况下,它只适用于构建)
  4. 因此,我使用了伴随where的{​​{1}}方法,以返回正确的值。我会用问题中的例子来说明答案。

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