6

現在、Factory Girl 4.1を使用したこれに対する最新の回答はありません(私が見つけたものです)-工場内で多対多の関係をどのように設定しますか?

たとえば、結合テーブルを使用して多対多の関係にある生徒教室があります。これまでのところ、次の設定があります。

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>

これを達成するための非推奨ではない構文を見つけることができなかったため、ほとんどの場合、私の試みは当て推量でした。

4

2 に答える 2

19

実際、私は探していた答えを、この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
于 2013-01-04T18:51:01.153 に答える
1

この SO 投稿をチェックしてください: How to setup factory in FactoryGirl with has_many association . https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.mdに移動します。has_manyを検索します。

于 2013-03-14T06:17:28.967 に答える