2010-09-03 58 views
3

我有这样一种关系:工厂女孩有很多的关系(和一个受保护的属性)

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
    attr_protected :article_id 
end 

内部控制器默认情况下是这样的:

@article = Article.create(:title => "foobar") 
@comment = @article.comments.create(:content => "w00t") 

我曾试图写那些工厂:

Factory.define :article do |f| 
    f.title "Hello, world" 
end 

Factory.define :comment do |f| 
    f.content "Awesome!" 
    f.association :article 
end 

但我的语法对关联不正确。由于评论的article_id受保护的属性,这有点棘手。所以我认为如果我在文章工厂内宣布这个协会,这应该会更好,但是我看不到如何处理。

感谢您的任何帮助。

回答

4

你应该做

Factory.define :comment do |f| 
    f.content "Awesome!" 
    f.article { |a| a.association(:article) } 
end 
+0

非常感谢,MB14。快乐的RoR3发展! :) – 2010-09-06 07:10:38