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

1 回答 1

4

你应该做

Factory.define :comment do |f|
  f.content "Awesome!"
  f.article { |a| a.association(:article) }
end
于 2010-09-03T10:52:02.363 回答