justsoftwareconsulting.com

October 12, 2009

FactoryGirl has_many associations

Filed under: Ruby On Rails — Tags: — rob @ 1:27 pm

Many many posts explain how to define FactoryGirl associations. None really seem how to do the simple case: ie: a has_many relationship with more than one child. The “documentation” certainly doesn’t. Maybe a Railscast does, but if I wanted to watch TV I wouldn’t be programming, would I?

Here’s a classic example of an unanswered question. Poor Umar wants this very same answer. He gets 3 wrong answers instead.

Anyway, here goes:

  • assume users, groups
  • users has_many groups
  • Factory for groups has the association back to the user, as follows (this is standard, BTW)

FactoryGirl definition:

Factory.define(:group) do |group|
  group.association :user
end 

Now, the key seems to be using it. One way is as follows:

@user=Factory(:user) # creates the user, user has 0 groups
[1 .. 3].each {|iii| @user.groups << Factory(:group, :user=>@user) } ## note the :user=>@user here - this is connecting the group the user, resolving Umars complaint.

So — near as I can tell, there is no automagic way to make FactoryGirl do what you’d want – ie, automatically create N child – but at least this comes close.

1 Comment »

  1. ??????? ??? ???????? ????, ?? ???????? ?? ???????????? ??? ????….

    < a href = “http://service.vektorwork.ru/2009/09/30/%d0%b0%d0%b4%d0%bc%d0%b8%d0%bd%d0%b8%d1%81%d1%82%d1%80%d0%b0%d1%82%d0%be%d1%80-21/” > < /a > Many many posts explain how to define FactoryGirl associations. None really seem how to do the simple cas…

    Trackback by Alex Gordon — April 4, 2010 @ 3:13 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

Powered by WordPress