Home > programming, rails > Factory Girl and has_many / has_many :through associations

Factory Girl and has_many / has_many :through associations

If you want to create has_many and has_many through associations in factory_girl as I once did, you will need to put it inside square brackets:

Factory.define :user do |user|
  user.name "My Name"
  user.groups {|groups| [groups.association(:group)]}
end

This will ensure that user.groups is not overriden by a single Group object, but by an array with a Group inside.

Categories: programming, rails Tags:
  1. February 11th, 2009 at 15:16 | #1

    If it wasn’t for excellent people like you – who find an answer to an annoying problem like this and then publish it to the world – people like me would spend hours hitting our heads against a brick wall. I salute you!

    Just started using Factory Girl and it looks really useful but, unless I’m being thick, I couldn’t find this in the rdoc.

  2. Umur
    March 16th, 2009 at 02:23 | #2

    I try your suggestion but…
    All groups end up with “user_id = nil”
    Using factory_girl 1.2.0

  3. March 16th, 2009 at 23:53 | #3

    can you tell us how your relationships are defined in the models so we can help you better?

  4. March 16th, 2009 at 23:57 | #4

    I’m sure you couldn’t, and that’s not your fault. It’s not there. I found it on a blog, but since I posted a few days after reading it, I could not remember the source, for what I am sorry.

  5. Umur
    March 17th, 2009 at 11:17 | #5

    I simply tried the suggestion making
    class User
    has_many :posts
    class Post
    belongs_to :user

    In the code above all groups end up with “user_id = nil”. Actually the factory creates the posts and the users. And the result is many unrelated posts and users.

    Can we consider it a bug or missing feature of factory girl?
    The one to many definition does not work:
    user.groups {|groups| [groups.association(:group)]}

  6. April 24th, 2009 at 15:28 | #6

    Umur,

    I was able to associate the child objects properly by ensuring they were written to the database when defining the lazy attribute, like so:

    user.groups {|groups| [Factory.create(:group)] }

    (.create writes the group to the database and ensures it has an ID, which the association then picks up on.)

  7. May 24th, 2009 at 11:33 | #7

    I had a huge problem creating these associations correctly w/ factory_girl, I finally got it fixed with help, you can check it out here: http://railsondave.blogspot.com/2009/05/creating-hasmany-through-factories-with.html

  1. October 15th, 2009 at 16:52 | #1