FactoryGirl 中的多对多关联如何工作?
可能的重复:
如何通过与装置关联来制作 has_many ?
我尝试使用 FactoryGirl 来构建我的测试数据。但我不知道如何建立多对多关联。
最后,我通过谷歌复制粘贴一个片段:(
factory :tagging do
question { |a| a.association(:question) }
tag { |a| a.association(:tag) }
end
通过标记询问 has_many 标签,反之亦然)
它效果很好。但这奇怪的语法是什么?当我在属性名称后面放置一个块时会发生什么?官方readme没有告诉我。
有人可以帮忙吗?
Possible Duplicate:
How to make has_many :through association with fixtures?
I tried use FactoryGirl to build my test data. But I don't know how to build many-to-many associations.
Finally, I google-copy-paste a snippet:
factory :tagging do
question { |a| a.association(:question) }
tag { |a| a.association(:tag) }
end
(question has_many tags through taggings, vice versa)
It works well. But what's this strange syntax? What's happen when I put a block after the attribute name? The official readme didn't tell me.
Could someone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所描述的
标记
模型至少有两列:question_id
和tag_id
。您可以手动设置它们,但您应该在此之前创建新对象。FactoryGirl
通过其关联功能为您做到这一点。它创建新对象(您将该对象的工厂指定为关联函数中的参数),获取其 id 并将其设置为适当的字段。As you described
tagging
model has at least two columns:question_id
andtag_id
. You can set them manually, but you should create new objects before that.FactoryGirl
does it for you through its association feature. It creates new object (you specify factory for that object as argument in association function), gets its id and sets it to appropriate field.