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 に答える