gpt4 book ai didi

ruby-on-rails - FactoryGirl has_many :through relationship broken in Rails 3. 2.11

转载 作者:行者123 更新时间:2023-11-28 20:04:54 24 4
gpt4 key购买 nike

一切都按预期工作,直到我升级到 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。因此,它在创建 :institute 时没有 student_id,使其无效。

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

我该如何解决这个问题?

最佳答案

像这样的东西怎么样

factory :student do |student|  
...
student.after_create do |student|
student.teachers << :teacher
end
end

关于ruby-on-rails - FactoryGirl has_many :through relationship broken in Rails 3. 2.11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14331308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com