如何在工厂女孩中创建 has_and_belongs_to_many 关联 [英] How to create has_and_belongs_to_many associations in Factory girl

查看:32
本文介绍了如何在工厂女孩中创建 has_and_belongs_to_many 关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下内容

class User < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

class Company < ActiveRecord::Base
  has_and_belongs_to_many :users
end

如何为公司和用户定义工厂,包括双向关联?这是我的尝试

how do you define factories for companies and users including the bidirectional association? Here's my attempt

Factory.define :company do |f|
  f.users{ |users| [users.association :company]}
end

Factory.define :user do |f|
  f.companies{ |companies| [companies.association :user]}
end

现在我试试

Factory :user

也许不出所料,这会导致无限循环,因为工厂递归地使用彼此来定义自己.

Perhaps unsurprisingly this results in an infinite loop as the factories recursively use each other to define themselves.

更令人惊讶的是,我在任何地方都没有提到如何执行此操作,是否有定义必要工厂的模式,或者我在做一些根本错误的事情?

More surprisingly I haven't found a mention of how to do this anywhere, is there a pattern for defining the necessary factories or I am doing something fundamentally wrong?

推荐答案

Factorygirl 已经更新,现在包括回调来解决这个问题.看看 http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl 了解更多信息.

Factorygirl has since been updated and now includes callbacks to solve this problem. Take a look at http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl for more info.

这篇关于如何在工厂女孩中创建 has_and_belongs_to_many 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆