如何制作has_many:通过与灯具的关联?

我不能使用factory_girl因为我正在测试太阳黑子,需要真正的数据库。

编辑 :不。 它可以与太阳黑子一起使用。 我错了。

如何在灯具中构建has_many:through(又名多对多)关联?

我谷歌并得到一个无效的解决方案

编辑

最后我使用factory_girl。 我google-copy-paste一个片段:

 factory :tagging do question { |a| a.association(:question) } tag { |a| a.association(:tag) } end 

(问题has_many标签通过标签,反之亦然)

它运作良好。 但它是什么? factory_girl的自述文件并不意味着这种语法。 有人能解释一下吗

你可以在这里找到factory_girl的官方文档,这是非常完整的。

这是一个很好的(较短的)博客文章解释factory_girl 2(与工厂女孩1比较)。

更新:

稍微解释一下代码:

  factory :tagging do association :tag end 

将寻找一个名为:tag的工厂并构造该对象,然后将其链接到对象内部的关联tag (例如, belongs_to:tagging

请注意:这是默认工厂。 如果您希望tag共享tag ,则需要执行类似的操作

 @tag = Factory(:tag) @tagging_1 = Factory(:tagging, :tag => @tag) @tagging_2 = Factory(:tagging, :tag => @tag) 

希望这可以帮助。

如果它是一个经典的has_and_belongs_to_many关联,在关联模型中没有其他信息,我认为约定允许你像这样编写你的灯具:

 #users.yml john: first_name: John last_name: Doe hobbies: [swim, play_tennis] #hobbies.yml swim: name: Swim play_tennis: name: Play Tennis 

但我不完全确定!

我使用fixtures测试has_many :through哈希merge

 # posts.yml one: title: "Railscasts" url: "http://railscasts.com/" description: "Ruby on Rails screencasts" # categories.yml one: name: "magazine" two: name: "tutorial" three: name: "news" four: name: "Ruby" # posts_controller_test.rb def test_post_create assert_difference 'Post.count' do post :create, post: posts(:one).attributes .merge(categories: [categories(:two), categories(:four)]) end end 

在添加另一个夹具文件后,尝试了这个并不起作用

 # post_categories.yml one: post: one category: two two: post: one category: four def test_post_create assert_difference 'Post.count' do post :create, post: posts(:one) end end puts posts(:one).attributes # {"id"=>980190962, "url"=>"http://railscasts.com/", "title"=>"Railscasts", "description"=>"Ruby on Rails screencasts", "created_at"=>Thu, 14 May 2015 18:27:20 UTC +00:00, "updated_at"=>Thu, 14 May 2015 18:27:20 UTC +00:00} puts posts(:one).attributes .merge(categories: [categories(:two), categories(:four)]) # {"id"=>980190962, "url"=>"http://railscasts.com/", "title"=>"Railscasts", "description"=>"Ruby on Rails screencasts", "created_at"=>Thu, 14 May 2015 18:30:23 UTC +00:00, "updated_at"=>Thu, 14 May 2015 18:30:23 UTC +00:00, "category_ids"=>[980190962, 1018350795]}