如何创建工厂女孩has_and_belongs_to_many协会 [英] How to create has_and_belongs_to_many associations in Factory girl

查看:123
本文介绍了如何创建工厂女孩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进行了更新,现在包括回调来解决这个问题。看看<一个href=\"http://robots.thoughtbot.com/post/254496652/aint-no-calla-back-girl\">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天全站免登陆