Rails 3 Factory Girl + Many to Many Relationships

不羁岁月 提交于 2019-12-23 09:34:06

问题


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

However this results in:

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.


回答1:


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



回答2:


Check out this SO post: How to set up factory in FactoryGirl with has_many association. It will point you to https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md; search for has_many.



来源:https://stackoverflow.com/questions/14162344/rails-3-factory-girl-many-to-many-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!