如何制作 has_many :通过与装置的关联? [英] How to make has_many :through association with fixtures?

查看:19
本文介绍了如何制作 has_many :通过与装置的关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用 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?

我在谷歌上搜索了一个无效的解决方案

编辑:

最后我使用 factory_girl.我谷歌复制粘贴一个片段:

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 的工厂并构造该对象,然后将其链接到关联 tag(例如一个 belongs_to) 存在于您的对象 :tagging 中.

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屋!

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