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

我的 factory.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,最后:student。因此,它没有student_id创建时间:institute,使其无效。

奇怪的是,相同的模型和 factory_girl 设置在 Rails 3.2.8 上运行良好。

我怎样才能解决这个问题 ?

4

2 回答 2

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 回答
2

这样的事情怎么办

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