在工厂中获得两个关联以共享另一个关联 [英] Get two associations within a Factory to share another association
问题描述
我有以下5个模型:监护人,学生,人际关系,RelationshipType和School.他们之间,我有这些关联
I've got these 5 models: Guardian, Student, Relationship, RelationshipType and School. Between them, I've got these associations
class Guardian < ActiveRecord::Base
belongs_to :school
has_many :relationships, :dependent => :destroy
has_many :students, :through => :relationships
end
class Student < ActiveRecord::Base
belongs_to :school
has_many :relationships, :dependent => :destroy
has_many :guardians, :through => :relationships
end
class Relationship < ActiveRecord::Base
belongs_to :student
belongs_to :guardian
belongs_to :relationship_type
end
class School < ActiveRecord::Base
has_many :guardians, :dependent => :destroy
has_many :students, :dependent => :destroy
end
class RelationshipType < ActiveRecord::Base
has_many :relationships
end
我想写一个定义关系的FactoryGirl.每个关系都必须有一名监护人和一名学生.这两个必须属于同一所学校.监护工厂与学校有联系,学生工厂也与学校有联系.我一直无法让它们在同一所学校建造.我有以下代码:
I want to write a FactoryGirl which defines a relationship. Every relationship must have a guardian and a student. These two must belong to the same school. The guardian factory has an association with school, and so does the student factory. I've been unable to get them to be built in the same school. I've got the following code:
FactoryGirl.define do
factory :relationship do
association :guardian
association :student, :school => self.guardian.school
relationship_type RelationshipType.first
end
end
当我尝试使用此工厂建立关系时,这会导致以下错误:
This results in the following error when I try to build a relationship using this factory:
undefined method `school' for #<FactoryGirl::Declaration::Implicit:0x0000010098af98> (NoMethodError)
有什么办法可以做我想要的事情,使监护人和学生属于同一所学校,而不必求助于将已经创建的监护人和学生送到工厂去(这不是它的目的)?
Is there any way to do what I want, to make the guardian and the student belong to the same school without having to resort to passing already created guardians and students to the factory (which is not its purpose)?
推荐答案
我认为这应该有效:
FactoryGirl.define do
factory :relationship do
association :guardian
relationship_type RelationshipType.first
after_build do |relationship|
relationship.student = Factory(:student, :school => relationship.guardian.school)
end
end
end
这篇关于在工厂中获得两个关联以共享另一个关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!