我有一个模型contact是has_many :locations, through: :relationships,还有has_many :teams, through: :contacts_teams。
联系人必须具有关联的team,location以便通过验证。换句话说:一个新的contact必须具有关联的relationship记录和关联的contacts_team记录。以下是模型:
#models/contact.rb class Contact < ActiveRecord::Base has_many :contacts_teams has_many :teams, through: :contacts has_many :relationships, dependent: :destroy has_many :locations, through: :relationships accepts_nested_attributes_for :contacts_teams, allow_destroy: true # upon create, validate that at least one associated team and one associated location exist validate :at_least_one_contacts_team validate :at_least_one_relationship private def at_least_one_contacts_team return errors.add :base, "Must have at least one Team" unless contacts_teams.length > 0 end def at_least_one_relationship return errors.add :base, "Must have at least one Location" unless relationships.length > 0 end end #models/contacts_team.rb class ContactsTeam < ActiveRecord::Base belongs_to :contact belongs_to :team end #models/team.rb class Team < ActiveRecord::Base has_many :contacts_teams has_many :contacts, through: :contacts_teams end #models/relationship.rb class Relationship < ActiveRecord::Base belongs_to :contact belongs_to :location end #models/location.rb class Location < ActiveRecord::Base has_many :relationships has_many :contacts, through: :relationships end
测试:使用factory_girl,我想创建一个contact能够成功创建contact记录的工厂。由于每条contact记录都需要一个关联的contacts_team记录和relationship记录:当我创建contact记录时,也应同时创建它们。同样:contacts_team记录应具有team与之关联relation的现有记录,并且记录应具有location与之关联的现有记录。因此从本质上讲,它也应该创建location和team记录。
如何创建与工厂的联系记录,实际上创建了关联的contacts_team记录和relationship记录?
这是我目前的工厂:
FactoryGirl.define do factory :contact do first_name "Homer" last_name "Simpson" title "Nuclear Saftey Inspector" end end FactoryGirl.define do factory :contacts_team do end end FactoryGirl.define do factory :team do name "Safety Inspection Team" end end FactoryGirl.define do factory :relationship do end end FactoryGirl.define do factory :location do name "Safety Location" end end
如果很难/不可能使用factory_girl进行此操作:如何使用直接rspec进行处理?问题是我无法创建一个contacts_team记录或一条relationship记录,因为与contact它关联的记录还不存在!而且我无法创建contact记录,因为关联的contacts_team记录或relationship记录尚不存在。似乎我被困住了,但是必须有一种做到这一点的方法。