6

Whats wrong with this before_save-callback?

class Order < ActiveRecord::Base

    has_many :line_items, :dependent => :destroy, :inverse_of => :order
    accepts_nested_attributes_for :line_items  
    attr_accessible :line_items_attributes


    before_save :mark_line_items_for_removal

    def mark_line_items_for_removal
      line_items.each do |line_item|
         line_item.mark_for_destruction if line_item.quantity.to_f <= 0
      end
    end
end

When one of the line_items are marked for destruction, no line_item will be saved. However the parent Order object does get saved. Returning true does not make a difference...

about mark_for_destruction: http://apidock.com/rails/v3.1.0/ActiveRecord/AutosaveAssociation/mark_for_destruction and why that instead of ":allow_destroy => true"? see here: http://weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/

NovapaX
  • 147
  • 1
  • 10
  • Maybe there is some problems with `if line_item.quantity.to_f <= 0`? Are you sure that it isn't always false, for example? – WarHog Nov 11 '11 at 22:51
  • Nope, i checked with 'puts line_item.marked_for_destruction?' after that line. It gave the expected result. But when one of them was marked, none of them got saved... – NovapaX Nov 11 '11 at 23:17
  • Did you ever found an answer for this? I noticed that marking children item for destruction would result in not saving bot marked and next item (IE: -1,1,2 - would save only 2) – bmihelac Mar 06 '12 at 06:38

1 Answers1

3

I believe you need to set the :autosave => true option for your has_many definition.

As stated, here:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

"If true, always save the associated objects or destroy them if marked for destruction, when saving the parent object. If false, never save or destroy the associated objects. By default, only save associated objects that are new records."

awaage
  • 2,429
  • 1
  • 15
  • 15