如何使用工厂女孩创建具有has_many的关联列表,并在创建时使用验证

时间:2012-05-02 20:29:30

标签: ruby-on-rails-3 factory-bot

在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”不是实例。所以这也不像以前那样有效。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

factory :article do
  reviewers {|a| [a.association(:reviewer)] }
end

factory :article do
  before_create do |a|
    FactoryGirl.create(:reviewer, article: a)
  end
end

答案 2 :(得分:1)

新语法是:

$change_data[$y]=$_POST['new']['location'][$y]);