我有以下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