# Has\_one association and saving the associated model

**URL:** <https://www.ruby-forum.com/t/has-one-association-and-saving-the-associated-model/104105>\
**Category:** Rails\
**Created:** [May 14, 2007, 11:30am UTC](https://www.ruby-forum.com/t/has-one-association-and-saving-the-associated-model/104105 "2007-05-14T11:30:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pixellover](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ee59a6/32.png) [@pixellover](https://www.ruby-forum.com/u/pixellover)\
**Post date:** [May 14, 2007, 11:30am UTC](https://www.ruby-forum.com/t/has-one-association-and-saving-the-associated-model/104105/1 "2007-05-14T11:30:38Z")

</div>

Hi,

what’s the best way of assigning a has\_one association to a model and  
then  
save both, the model and the association, in one step? I  
thought “build\_association” just assigns the association and not updates  
it  
in the database.

In my current situation this leads to a double saving of my association.  
First  
it get’s updated an then a new association gets created.

I’ve two models: “client” and “birthday”. Birthday is a has\_one  
association of  
client:

class Client \< ActiveRecord::Base  
has\_one :birthday, :dependent =\> :destroy  
end

In the “update” action of the client controller I’ve something like  
this:

def update  
@client = Client.find(params[:id])  
@client.attributes = params[:client]  
@client.build\_birthday(params[:birthday])

```
respond_to do |format|
    if @client.save
        format.html { redirect_to client_url(@client) }
        format.xml { head :ok }
    else
        format.html { render :action => "edit" }
        format.xml { render :xml => @client.errors.to_xml }
    end
end

```

end

First, when executing the line  
@client.build\_birthday(params[:birthday]), the  
current associated birthday object in the database gets updated. Next,  
when  
@client.save gets executed, a new birthday-object gets created in the  
database (and the foreign key of the old entry gets deleted). This leads  
to  
many, not assigned entrys in my database.

If I just use @client.birthday.attributes = params[:birthday] instead of  
build\_birthday, no birthday at all gets saved. So, what’s the best was  
of  
assigning a has\_one association without saving it?

Regards,  
Timo

---

<div class="post-metadata">

**Author:** ![pixellover](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/ee59a6/32.png) [@pixellover](https://www.ruby-forum.com/u/pixellover)\
**Post date:** [May 14, 2007, 11:30am UTC](https://www.ruby-forum.com/t/has-one-association-and-saving-the-associated-model/104105/2 "2007-05-14T11:30:38Z")

</div>

dear sender,  
i´m out of the office until may 29th.  
your email will not be forwarded.  
for urgent stuff please contact removed\_email\_address@domain.invalid  
kind regards,  
alexander
