简体   繁体   中英

Can't build has_many association with Factory Girl

I have a User that has_many posts in Rails 4.1.6. Following the Getting Started page for Factory Girl , I have created these factories:

factory :post do
  skip_create
  title 'foo bar'
  user
end

factory :user do
  skip_create
  id 1
  username 'alice'

  factory :user_with_posts do
    skip_create

    transient do
      posts_count 5
    end

    after(:build) do |user, evaluator|
      build_list(:post, evaluator.posts_count, user: user)
    end
  end
end

But calling build(:user_with_posts) returns a User with an empty posts array. Calling build_list(:post, 5, user: user) (with a pre-built User ) works.

What am I missing?

Also, is there a way to set a global skip_create so I don't have to set it on each factory?

I had a similar problem, and all according to all the docs I was reading, it should have been working. Here is what finally worked (adapted for your code):

change

build_list(:post, evaluator.posts_count, user: user)

to

user.posts = build_list(:post, evaluator.posts_count, user: user)

Let me know if that doesn't work, but that's what solved it for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM