gpt4 book ai didi

ruby-on-rails - 在一个工厂中获取两个关联以共享另一个关联

转载 作者:行者123 更新时间:2023-12-03 12:48:19 24 4
gpt4 key购买 nike

我有这 5 个模型:Guardian、Student、Relationship、RelationshipType 和 School。他们之间,我有这些联想

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)

有没有办法做我想做的事,让监护人和学生属于同一所学校,而不必诉诸将已经创建的监护人和学生传递给工厂(这不是它的目的)?

最佳答案

有更简洁的方式来编写这个关联。答案来自 this github issue .

FactoryGirl.define do
factory :relationship do
association :guardian
student { build(:student, school: relationship.guardian.school) }
relationship_type RelationshipType.first
end
end

关于ruby-on-rails - 在一个工厂中获取两个关联以共享另一个关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820114/

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