【发布时间】:2017-03-05 00:58:13
【问题描述】:
class Program < ActiveRecord::Base
has_many :contacts
class Contact < ActiveRecord::Base
belongs_to :program
FactoryGirl.define do
factory :contact do
sequence(....
...
program_id 1 #foreign key
program #association
(byebug) contact
Contact id: 949, display_name: "Contact-3", business_phone: "1234567894", fax_number: "1234567894", created_at: "2017-03-05 00:43:24", updated_at: "2017-03-05 00:43:24", first_name: "First-4", last_name: "Last-4", middle_initial: "4", email: "Email4@Something.Com", program_id: 1193, 287g: nil, active: true, call_office_id: 4
在使用联系人工厂创建的联系人记录中,program_id 为 1193,但程序表中只有 4 条 id 为 1-4 的记录。不确定 1193 的来源。在这一点上,rspec 测试或多或少地成功了。但是一旦下面的验证代码被添加到联系人模型中,rspec 测试就会失败。
为程序添加关联验证的联系模型
class ProgramValidator < ActiveModel::Validator
def validate(record)
if record.program.nil?
record.errors[:base] << "Program cannot be blank"
end
end
end
class Contact < ActiveRecord::Base
belongs_to :program
validates_with ProgramValidator
现在运行 rspec,它抱怨“程序不能为空白”。问题:如何创建联系工厂以满足验证?为什么关联这么难,比在 ROR 中创建关联要困难得多。感谢阅读。
【问题讨论】:
标签: ruby-on-rails validation associations