Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to user factory girl to create associated lists with a has_many with a validation that requires it on create
    primarykey
    data
    text
    <p>In a Rails application, given three models User, Article and Reviewer with the following relationships and validations:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :articles has_many :reviewers end class Reviewer &lt; ActiveRecord::Base belongs_to :user belongs_to :article end class Article &lt; 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 </code></pre> <p>And the following factories using the newer DSL:</p> <pre><code>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 </code></pre> <p>The factory to create the article doesn't work because the validation fails before the reviewers are created:</p> <pre><code>&gt; FactoryGirl.create(:article) ActiveRecord::RecordInvalid: Validation failed: article must have at least one reviewer. </code></pre> <p>I have made more attempts than I would like to admit trying to overcome this hurdle, but I am stuck! One idea I had was to create the reviewers like this:</p> <pre><code> factory :article do body "This is the article content" title "This is the title" user reviewers {|a| [FactoryGirl.create(:reviewer, article: a)] } end </code></pre> <p>but in this context, the "a" is not the instance. So that doesn't work either, like it used to.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload