# Factory\_girl: build associated object

**URL:** <https://www.ruby-forum.com/t/factory-girl-build-associated-object/182579>\
**Category:** Rails\
**Created:** [January 30, 2010, 9:33am UTC](https://www.ruby-forum.com/t/factory-girl-build-associated-object/182579 "2010-01-30T09:33:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Learn\_by\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e274bd/32.png) [@Learn\_by\_D](https://www.ruby-forum.com/u/Learn_by_D)\
**Post date:** [January 30, 2010, 9:33am UTC](https://www.ruby-forum.com/t/factory-girl-build-associated-object/182579/1 "2010-01-30T09:33:31Z")

</div>

I am using factory girl to build the following objects: user and  
blog. A user has one blog. A blog belongs to a user.

When I do the following

Factory.define :user do |u|  
u.association :blog  
end

I get this error: Mysql::Error: Column ‘user\_id’ cannot be null: . I  
suspect that is because factory tries to build a blog before it saves  
the associated user object. I am getting around this problem by  
creating the associated blog in the steps file:

Given /^"([^"]\*)" is a screen name of a user$/ do |user\_screen\_name|  
user = User.find\_by\_screen\_name(user\_screen\_name)  
if user.nil?  
user = Factory.create(:user, :screen\_name =\> user\_screen\_name)  
Factory.create(:blog, :user\_id =\> user.id)  
end  
end

This works but I don’t think it’s very elegant. What do you think?  
Thanks.
