Using association's attributes in definition

310 views
Skip to first unread message

Phil

unread,
Nov 24, 2009, 5:09:48 AM11/24/09
to factory_girl
I need to define a factory that uses an attribute from it's
association, but I keep getting a whiny nil error:

Factory.define(:comment) do |c|
c.article { |article| article.association(:article) }
c.article_author_name { c.article.author.name }
end

At this point it complains article is nil, so I'm calling author on
nil. Is there any way to do this?

Nathan Sutton

unread,
Nov 24, 2009, 2:26:40 PM11/24/09
to factor...@googlegroups.com
Try this:

Factory.define(:comment) do |c|
c.association :article
c.article_author_name {|o| o.article.author.name}
end
> --
> Individuals over processes. Interactions over tools. Agile Rails training from thoughtbot, the makers of Clearance, Shoulda, & Factory Girl:
> http://thoughtbot.com/services/training
>
> You received this message because you are subscribed to the "factory_girl" mailing list.
> To post to this group, send email to factor...@googlegroups.com
> To unsubscribe from this group, send email to
> factory_girl...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/factory_girl?hl=en

Phil

unread,
Nov 24, 2009, 4:25:28 PM11/24/09
to factory_girl
I figured out my problem. When you define the association in a parent
factory, for whatever reason you can't call attributes in the child
factory. (ie the article association is defined in a parent factory,
in the child factory you can't use the article.author.name)

I ended up having to redefine the association in the child factory.

Nathan Sutton

unread,
Nov 26, 2009, 9:02:54 PM11/26/09
to factor...@googlegroups.com
On Tue, Nov 24, 2009 at 3:25 PM, Phil <phuib...@gmail.com> wrote:
> I ended up having to redefine the association in the child factory.

That's pretty strange. You could also use one of the fg callbacks to
grab the value of the association, if you wanted to.

Doug

unread,
Dec 29, 2009, 5:18:22 PM12/29/09
to factory_girl
I came across a similar scenario: for an Occurence, both Event and
Venue must belong to the same Organization.

The following worked for me:

Factory.define :event do |f|
f.association :organization
f.name { "Event: #{Faker::Lorem.words(3).join(" ").titleize}" }
end

Factory.define :venue do |f|
f.association :organization
f.name { "Venue: #{Faker::Lorem.words(2).join(" ").titleize}" }
end

Factory.define :occurence do |f|
f.event { |o| o.association(:event) }
f.venue { |o| o.association(:venue, :organization =>
o.event.organization) }
...
end

Your tip helped - thanks Nathan.


On Nov 27, 4:02 am, Nathan Sutton <nathan.sut...@gmail.com> wrote:

Reply all
Reply to author
Forward
0 new messages