0

我有一个模型公司,它接受招聘人员模型的嵌套属性。我需要在我的公司模型中验证在公司创建期间至少创建了一名招聘人员。

class Company < ActiveRecord::Base
    has_many :recruiters, dependent: :destroy, inverse_of: :company
    accepts_nested_attributes_for :recruiters, reject_if: ->(attributes) { attributes[:name].blank? || attributes[:email].blank? }, allow_destroy: true

    validate { check_recruiters_number } # this validates recruiters number

    private

    def recruiters_count_valid?
       recruiters.reject(&:marked_for_destruction?).count >= RECRUITERS_COUNT_MIN
    end

    def check_recruiters_number
       unless recruiters_count_valid?
           errors.add(:base, :recruiters_too_short, count: RECRUITERS_COUNT_MIN)
       end
    end
end

验证按预期工作,但添加此验证后,FactoryGirl 出现问题。我的公司工厂是这样的:

FactoryGirl.define do
   factory :company do
        association :industry
        association :user
        available_disclosures 15
        city 'Berlin'
        country 'Germany'

        ignore do
            recruiters_count 2
        end

        after(:build) do |company, evaluator|
            FactoryGirl.create_list(:recruiter, evaluator.recruiters_count, company: company)
        end

        before(:create) do |company, evaluator|
            FactoryGirl.create_list(:recruiter, evaluator.recruiters_count, company: company)
        end
    end 
end  

在测试中,当我这样做时

company = create(:company)

我收到验证错误:

ActiveRecord::RecordInvalid:
   Validation failed: Company has to have at least one recruiter

当我第一次建立公司然后保存它时,测试通过了:

company = build(:company)
company = save

当然,我不想以这种方式更改我的所有测试以使其正常工作。在创建公司模型期间如何设置我的工厂以创建关联模型?

4

2 回答 2

1

validate { check_recruiters_number }的不合理。去掉它。

为什么?您需要有一个有效的公司 ID 才能保存招聘人员,但您的验证器阻止公司有效,因为它没有招聘人员。这是矛盾的。

于 2013-08-31T08:08:08.527 回答
1

这是一个老问题,但我有类似的问题,我用以下代码解决了它(重写以匹配你的情况):

FactoryGirl.define do
   factory :company do
        association :industry
        association :user
        available_disclosures 15
        city 'Berlin'
        country 'Germany'

        ignore do
            recruiters_count 2
        end

        after(:build) do |company, evaluator|
            company.recruiters = FactoryGirl.build_list(:recruiter, evaluator.recruiters_count, company: company)
        end
    end 
end
于 2016-05-26T19:12:14.070 回答