我有以下5个模型:监护人,学生,关系,关系类型和学校。在他们之间,我有这些协会在工厂内部获得两个关联以共享另一个关联
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)
有没有办法做我想做什么,让监护人和学生同属一所学校,而不必诉诸已经建立的监护人和学生到工厂(这不是它的目的)?
我不确定这是否与错误有关,但School类是作为第二个关系类声明(编辑之前)编写的。 – PinnyM 2012-01-11 23:02:34