我有一个模型公司,它接受招聘人员模型的嵌套属性。我需要在我的公司模型中验证在公司创建期间至少创建了一名招聘人员。
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
当然,我不想以这种方式更改我的所有测试以使其正常工作。在创建公司模型期间如何设置我的工厂以创建关联模型?