Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails factorygirl关联验证 类程序_Ruby On Rails_Validation_Associations - Fatal编程技术网

Ruby on rails factorygirl关联验证 类程序

Ruby on rails factorygirl关联验证 类程序,ruby-on-rails,validation,associations,Ruby On Rails,Validation,Associations,在使用contact factory创建的contact记录中,program_id为1193,但program表中只有四条id为1-4的记录。不确定1193的来源。此时rspec测试或多或少成功。但一旦将下面的验证代码添加到contact模型中,rspec测试将失败 为程序添加关联验证的联系人模型 class Program < ActiveRecord::Base has_many :contacts class Contact < ActiveRecord::Base bel

在使用contact factory创建的contact记录中,program_id为1193,但program表中只有四条id为1-4的记录。不确定1193的来源。此时rspec测试或多或少成功。但一旦将下面的验证代码添加到contact模型中,rspec测试将失败

为程序添加关联验证的联系人模型

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
class ProgramValidatorrecord.errors[:base]根据Factory Girl的文档,尝试以下操作:

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
有关工厂女孩协会的更多信息,请访问以下链接: 这是:

factory :contact do
  # ...
  association :program, factory: :program
end
创建新的程序记录,该记录作为关联附加(与其他id,也可以是1193或任何其他id)

如果您不想创建任何新的程序记录,只需将
program_id 1
保留在factory类中即可。另外,请记住,您在空数据库中运行测试。 例如,如果您在测试套件之前创建程序记录并将其ID显式指定为1,则此工厂类定义将起作用

FactoryGirl.define do
  program       #association