我有这5个模型:Guardian(监护人),Student(学生),Relationship(关系),RelationshipType(关系类型)和School(学校)。它们之间有以下关联:
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来定义一个关系。每个关系必须有一个监护人和一个学生,这两个人必须属于同一所学校。监护人工厂与学校有一个关联,学生工厂也是如此。但我一直无法让它们在同一所学校中创建。我有以下代码:
FactoryGirl.define do
factory :relationship do
association :guardian
association :student, :school => self.guardian.school
relationship_type RelationshipType.first
end
end
使用这个工厂构建关系时,会导致以下错误:
undefined method `school' for #<FactoryGirl::Declaration::Implicit:0x0000010098af98> (NoMethodError)
有没有什么方法可以实现我想要的,让监护人和学生属于同一所学校,而不必通过将已创建的监护人和学生传递给工厂(这不是它的目的)来实现?