を作成する上で、それを必要とし、検証してhas_manyの関連付けられたリストを作成するには、工場出荷時の女の子、以下の関係および検証で3つのモデルユーザー、記事やレビューを与えた:どのようにユーザーのRailsアプリケーションで
class User < ActiveRecord::Base
has_many :articles
has_many :reviewers
end
class Reviewer < ActiveRecord::Base
belongs_to :user
belongs_to :article
end
class Article < ActiveRecord::Base
belongs_to :user
has_many :reviewers
validate :has_reviewers?
def has_reviewers?
errors.add(:base, "article must have at least one reviewer.") if self.reviewers.blank?
end
end
をそして、新しいDSLを使用して、次の工場:検証が失敗したので、動作しません。記事を作成するために、工場は
FactoryGirl.define do
factory :user do
name { (8...20).map{ ('a'..'z').to_a[rand(26)] }.join }
age { Kernel.rand(100) }
end
factory :article do
body "This is the article content"
title "This is the title"
user
after_create do |article|
article.reviewers = create_list(:user, 2)
end
end
factory :reviewer do
user
article
state { ["published","draft","rejected","archived"][Kernel.rand(4)] }
end
end
レビューアが作成される前に:
> FactoryGirl.create(:article)
ActiveRecord::RecordInvalid: Validation failed: article must have at least one reviewer.
私はこのハードルを克服しようとしているよりも多くの試みをしましたが、私は立ち往生しています!私が持っていたひとつのアイデアは、このように査読を作成することでした。
factory :article do
body "This is the article content"
title "This is the title"
user
reviewers {|a| [FactoryGirl.create(:reviewer, article: a)] }
end
が、この文脈で
は、「」インスタンスではありません。だから、それは昔のようにどちらもうまくいかない。
は、私が取得:SystemStackError:スタックレベルが深すぎ。査読者の工場が解雇されたとき、その執行品について知りませんので、もう1つの記事を作成しようとしているようです。 – Blizzo
@Blizzoレビュアーファクトリから記事の作成を削除するか、before_createを使用することができます。私はそれを反映するために私の答えを編集しました。 – Unixmonkey
ActiveRecord :: RecordInvalid:検証に失敗しました:記事に少なくとも1人のレビューアがもう一度いる必要があります – Blizzo