如何使has_many:通过与灯具关联? [英] How to make has_many :through association with fixtures?
问题描述
我不能使用factory_girl
,因为我正在测试黑子并且需要真实的数据库.
I can't use factory_girl
because I'm testing sunspot and need real database.
修改:不.它可以与黑子一起使用.我错了.
Edit: nope. It can works with sunspot. I'm wrong.
如何在灯具中建立has_many:through(也称为多对多)关联?
How can I build has_many :through(a.k.a many-to-many) associations in fixtures?
我用Google搜索它,并得到了无效的解决方案
I google it and get a invalid solution
修改:
最后,我使用factory_girl.我用google复制并粘贴了一个代码段:
Finally I use factory_girl. I google-copy-paste a snippet:
factory :tagging do
question { |a| a.association(:question) }
tag { |a| a.association(:tag) }
end
(通过标签有问题has_many标签,反之亦然)
(question has_many tags through taggings, vice versa)
效果很好.那是什么factory_girl的自述文件并不意味着该语法. 有人可以解释吗?
It works well. But what's it? The factory_girl's readme didn't meantion this syntax. Could someone explain?
推荐答案
您可以找到有关factory_girl的正式文档,该文档非常完整,
You can find the official documentation for factory_girl, which is very complete, here.
此处是一篇很好的(简短的)博客文章,解释了factory_girl 2(进行比较和工厂女工1).
Here is a nice (shorter) blogpost explaining factory_girl 2 (comparing it with factory-girl 1).
已更新:
稍微解释一下代码:
factory :tagging do
association :tag
end
将寻找一个名为:tag
的工厂,并将构造该对象,然后将其链接到对象:tagging
内部存在的关联tag
(例如,belongs_to
).
will look for a factory called :tag
and will construct that object, and then link that to the association tag
(e.g. a belongs_to
) that is there inside your object :tagging
.
请注意:这是默认出厂.如果要taggings
共享tag
,则需要执行类似的操作
Please note: this is the default factory. If you want taggings
to share a tag
, you will need to do something like
@tag = Factory(:tag)
@tagging_1 = Factory(:tagging, :tag => @tag)
@tagging_2 = Factory(:tagging, :tag => @tag)
希望这会有所帮助.
这篇关于如何使has_many:通过与灯具关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!