# Saving belongs\_to associations

**URL:** <https://www.ruby-forum.com/t/saving-belongs-to-associations/141464>\
**Category:** Rails\
**Created:** [June 26, 2008, 2:21am UTC](https://www.ruby-forum.com/t/saving-belongs-to-associations/141464 "2008-06-26T02:21:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jeff\_Lee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8797f3/32.png) [@Jeff\_Lee](https://www.ruby-forum.com/u/Jeff_Lee)\
**Post date:** [June 26, 2008, 2:21am UTC](https://www.ruby-forum.com/t/saving-belongs-to-associations/141464/1 "2008-06-26T02:21:42Z")

</div>

I’m trying to save a username along with profiles (User has\_many  
Profiles; Profile belongs\_to User). I had a portion of this working  
(updating user info) but I cannot create new user records.  
I get the following error:

You have a nil object when you didn’t expect it!  
The error occurred while evaluating nil.build

Parameters:  
{“commit”=\>“Create record”,  
“profile”=\>{“company”=\>"",  
“new\_user\_attributes”=\>[{“username”=\>“jlee”,  
“active”=\>“1”}],  
“new\_someid\_attributes”=\>[{“someid”=\>“123456789”}],  
“type\_id”=\>“2”,  
“first\_name”=\>“Jeffrey”,  
“last\_name”=\>“Lee”},  
“authenticity\_token”=\>“65507986d1912380edf522b5b9f7ee3763c6dc0d”}

I am getting stuck on the profile model code below:

# Users

def new\_user\_attributes=(user\_attributes)  
user\_attributes.each do |attributes|  
user.build(attributes)  
end  
end  
def existing\_user\_attributes=(user\_attributes)  
user.reject(&:new\_record?).each do |user|  
attributes = user\_attributes[user.id.to\_s]  
if attribute  
user.attributes = attributes  
else  
user.delete(email)  
end  
end  
end  
def save\_user  
user.save(false)  
end

New method in profiles\_controller:  
def new  
@profile = Profile.new  
@profile.user = User.new  
end

User partial:

 \<% new\_or\_existing = user.new\_record? ? 'new' : 'existing' %\> \<% prefix = "profile[#{new\_or\_existing}\_user\_attributes][]" %\> \<% fields\_for prefix, user do |user\_form| -%\> \<%= label :user\_form, :user, "Username" %\>\<%= user\_form.text\_field :username %\> \<%= user\_form.hidden\_field :active, :value =\> "1" %\> \<% end -%\>
