如何将用户的工厂女孩​​创建相关联的列表与验证一个的has_many需要它的创建(How to us

2019-07-29 06:17发布

在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

但在此背景下,“一”是不是实例。 这样也不行,像以前那样。

Answer 1:

我转贴的工厂女孩​​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



Answer 2:

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

要么

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


Answer 3:

新的语法是:

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


文章来源: How to user factory girl to create associated lists with a has_many with a validation that requires it on create