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