2

Rails 3.2.11にアップグレードするまで、すべてが期待どおりに機能していました。

これが私のモデルのセットアップ方法です:

class Student < ActiveRecord::Base
    has_many :institutes
    has_many :teachers, :through => :institutes
end

class Teacher < ActiveRecord::Base
    has_many :institutes
    has_many :students, :through => :institutes
end

class Institute < ActiveRecord::Base
    belongs_to :teachers
    belongs_to :students
    validates :teacher_id, :presence => true
    validates :student_id, :uniqueness => {:scope  => :teacher_id}, :presence => true
end

私のfactories.rbファイルは次のようになります:

factory :student do
    first_name "abc"
    last_name "xyz"
    teachers {|t| [t.association(:teacher)] }
end

factory :teacher do
    first_name "ABC"
    last_name "XYZ"
end

factory :institute do
    association :student
    association :teacher
end

問題 :

私がする時 :

FactoryGirl.create(:student)

次のエラーが発生します:

ActiveRecord::RecordInvalid: Validation failed: Institutes is invalid

のように、それは:teacher:instituteそして最後に作成します:studentstudent_idしたがって、作成時のがないため、:institute無効になります。

奇妙なことに、同じモデルとfactory_girlのセットアップがRails3.2.8で正常に機能していました。

どうすればこれを修正できますか?

4

2 に答える 2

2

このようなものはどうですか

factory :student do |student|  
  ...
  student.after_create do |student|  
    student.teachers << :teacher  
  end  
end  
于 2013-01-15T08:56:59.490 に答える
2

試す:

factory :student do
    first_name "abc"
    last_name "xyz"
end

factory :teacher do
    first_name "ABC"
    last_name "XYZ"
end

factory :institute do
    student
    teacher
end

それで:

@institute = FactoryGirl.create(:institute)
@student = @institute.student

これは検証で機能します。

于 2013-01-15T09:03:35.160 に答える