2010-09-03 57 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