问题描述
使用Factory Girl 4.1(我能找到)目前没有最新的答案-您如何在工厂内部建立多对多关系?
There aren't currently any up to date answers for this using Factory Girl 4.1 (that I could find) - how do you setup a many to many relationship inside of a factory?
例如,我有学生和教室,它们使用联接表具有多对多关系,到目前为止,我具有以下设置:
For instance I have Students and Classrooms which are in a many to many relationship using a join table, so far I had the following setup:
factory :classroom do
name "Foo Class"
...
end
factory :student do
name "John Doe"
...
end
factory :student_with_classroom, :parent => :student do
after(:build) {|student| student.classrooms << classroom}
end
但这会导致:
NameError:
undefined local variable or method `classroom' for #<FactoryGirl::SyntaxRunner>
我的大部分尝试都是猜测,因为我没有运气找到任何不赞成使用的语法来完成此任务.
My attempt was guesswork for the most part as I had no luck finding any non-deprecated syntax to accomplish this.
推荐答案
实际上,我设法找到了我一直在寻找的答案,这些答案隐藏在这样的其他答案中:
Actually I managed to find the answer I was looking for buried under a slew of other answers in this SO: How to create has_and_belongs_to_many associations in Factory girl
factory :classroom do
name "Foo Class"
...
end
factory :student do
name "John Doe"
...
end
factory :student_with_classroom, :parent => :student do
classrooms {[FactoryGirl.create(:classroom)]}
end
这篇关于Rails 3 Factory Girl +多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!