Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

nested attributes vs before_save

#3391

When a nested attribute class returns false in its before_save hook, the main class still saves, and the child object silently disappears, and save returns true. Observe:

# user.rb
class User < ActiveRecord::Base
    has_many :posts
    accepts_nested_attributes_for :posts
end

#post.rb
class Post < ActiveRecord::Base
    belongs_to :user
    before_save :return_false
    def return_false
      false
    end
end

# in console
>> User.new(:name=>'bug2', :posts_attributes=>[:body=>'test2']).save!
=> true
>> User.all
=> [#<User id: 4, name: "bug2">]
>> Post.all
=> []

I think it should throw an exception (or return false in case of "save" method)

Reported by Marcin Mańk · October 18th, 2009 @ 07:07 PM

State: resolved
Milestone: 2.3.6
Assigned to: Eloy Duran Eloy Duran
Importance: none

Activity

  1. Marcin Mańk
    Marcin Mańk
    • Tag changed from attributes, nested to accepts_nested_attributes_for, before

    October 30th, 2009 @ 06:52 PM

  2. Eloy Duran
    Eloy Duran
    • Assigned user set to Eloy Duran
    • Milestone set to 2.3.6

    December 30th, 2009 @ 07:50 PM

  3. Repository
    Repository
    • State changed from new to resolved

    (from [f2aacd51405724cdf7cfd36a439c9dbfce16973a]) Rollback the transaction when one of the autosave associations fails to save. [#3391 nested attributes vs before_save state:resolved] http://github.com/rails/rails/commit/f2aacd51405724cdf7cfd36a439c9d...

    January 8th, 2010 @ 11:24 PM

  4. Repository