Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord associations are auto-saved on assignment after migrating between Rails versions, how can I disable that?

I'm trying to migrate my application from Rails 3.0.7 to Rails 3.1.3. I have 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 controller's 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 second line of this code I'm getting error:

Failed to save the new associated contact_address.

So it seems that assignment to @client.contact_address somehow triggered save method on contact_address object... I do not want that... Is this some new Rails 3.1.x behavior? I want associated objects to save only when I call .save! on parent model - this is too much magic for me. Can I disable this behavior somewhere?

like image 715
Adrian Serafin Avatar asked Jan 20 '12 23:01

Adrian Serafin


1 Answers

I've found workaround for this. In controllers edit method I've used build method instead of 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 intrested to read about this new behavior somewhere (my googling was unsuccessfull). Maybe someone could provide a link?

like image 91
Adrian Serafin Avatar answered Oct 02 '22 20:10

Adrian Serafin