brad
brad

Reputation: 32355

ActiveRecord autosave:false doesn't appear to work

According to the docs, setting :autosave => false on an association should NOT save those associations when you save the parent. This doesn't appear to work for me. I just created a vanilla Rails 3.0.8 app and here's what I get:

class Foo < ActiveRecord::Base
  has_many :bars, :autosave => false
  accepts_nested_attributes_for :bars
end

class Bar < ActiveRecord::Base
  belongs_to :foo
end

f = Foo.new :name => 'blah', :bars_attributes => [{:name => 'lah'},{:name => 'lkjd'}]
f.save
f.bars
 => [#<Bar id: 1, name: "lah", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">, #<Bar id: 2, name: "lkjd", foo_id: 1, created_at: "2011-06-20 20:51:02", updated_at: "2011-06-20 20:51:02">]

What?? Why did it save the bars?

I feel like I'm taking crazy pills!! What am I missing?

Update: It appears as if accepts_nested_attributes_for automatically saves children, even if they're not built using the nested attributes feature. It think this is a bug.

Upvotes: 3

Views: 1786

Answers (2)

helder.tavares.silva
helder.tavares.silva

Reputation: 734

Adding to Innerpeacer response, it doesn't make sense setting the autosave attribute to false if you are using accepts_nested_attributes_for. One of the reasons to use accepts_nested_attributes_for is to save children and parent at the same time.

What you can do is:

f = Foo.new :name => 'blah'
f.save
f.bars_attributes = [{:name => 'lah'},{:name => 'lkjd'}]

or

f = Foo.new :name => 'blah'
f.save
f.bars = [Bars.new({:name => 'lah'}), Bars.new({:name => 'lkjd'})]

Upvotes: 0

Innerpeacer
Innerpeacer

Reputation: 1321

This is not a bug, instead it is intended. see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

A click on "Source: show" on method accepts_nested_attributes_for also proves this.

Note that the :autosave option is automatically enabled on every association that accepts_nested_attributes_for is used for.

Upvotes: 5

Related Questions