18

在 Rails 应用程序中,给定三个模型 User、Article 和 Reviewer,具有以下关系和验证:

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

但在这种情况下,“a”不是实例。所以这也不起作用,就像以前一样。

4

3 回答 3

22

我将此作为问题重新发布在 Factory Girl github 页面上,并努力寻找答案:

before_create do |article|
  article.reviewers << FactoryGirl.build(:reviewer, article: article)
end

关键是在 before_create 中执行此操作,因此尚未触发验证,并确保将新创建的审阅者推送到正在创建的实例的审阅列表中。感谢 Unixmonkey 响应并让我尝试新事物 :)

https://github.com/thoughtbot/factory_girl/issues/369#issuecomment-5490908

于 2012-05-03T16:32:58.057 回答
3
factory :article do
  reviewers {|a| [a.association(:reviewer)] }
end

或者

factory :article do
  before_create do |a|
    FactoryGirl.create(:reviewer, article: a)
  end
end
于 2012-05-02T20:44:27.417 回答
1

新语法是:

before(:create) do |article|
  article.reviewers << FactoryGirl.build(:reviewer, article: article)
end
于 2016-08-25T15:16:21.827 回答