Rails, factory_girl and has_many

by jan on April 4th, 2010

This is just a quick note that some people might find useful. I do not write factory_girl Factories that often and when I do I always keep its RDoc opened up because I never seem to remember the API (after not using it for a while).

The problem I had few times before and the problem I set out to fix today was: “What to do when you want to create multiple objects for your has_many association?” Now, this seems like a simple task for factory_girl callbacks. I tried many approaches, this is my final one and I am happy it works.

Lets say we have a model Bundle and it has_many BundleItems. Then a factory that creates a Bundle with exactly four BundleItems will look like this:

Factory.define :bundle do |f|
  f.bundle_items do |bundle|
    res = []
    4.times do
      res << Factory.build(:bundle_item, :bundle => bundle.result)
    end
    res
  end
end

The only thing I am quite unhappy about is that this calls Proxy.result sooner than it would originally happen, but I simply do not see a better way around this. Suggestions are welcome!

From Rails

1 Comment
  1. Rick R permalink

    Thanks for posting this. It helped me.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS