ActiveRecord associations are automatically saved upon assignment after migration between versions of Rails, how can I disable this?

I am trying to port my application from Rails 3.0.7 to Rails 3.1.3. I have a client model

class Client::Client < ActiveRecord::Base has_one :contact_address, :class_name => "Address", :foreign_key => :client_id, :conditions => ["kind = ? and state = ?", 2, 1] end 

In the controller edit method, I execute this code:

 def edit @client = params[:type].classify.constantize.find params[:id] @client.contact_address = Address.new(:kind => 2) if @client.contact_address.blank? end 

In the second line of this code, I get an error:

 Failed to save the new associated contact_address. 

So it seems that the @ client.contact_address assignment somehow called the contact_address object persistence method ... I don't want this ... Is this some new Rails 3.1.x behavior? I want related objects to be saved only when .save is called! on the parent model - for me it's too much. Can I disable this behavior somewhere?

+8
activerecord ruby-on-rails-3
source share
1 answer

I found a workaround for this. In the controller edit method, I used the build method instead of the assignment:

 def edit @client = params[:type].classify.constantize.find params[:id] @client.build_contact_address(:kind => 2) if @client.contact_address.blank? end 

But I'm still interested in reading about this new behavior somewhere (my Google search was not unsuccessful). Maybe someone can provide a link?

+8
source share

All Articles