Re: nested forms - how to use before/after destroy callback ?

Javix
2013-03-19T14:30:24Z

So still no idea how to avoid the destroy of the last association. I do all
the processing in the ''update '' action of
TimesheetsController. I tried
with ''after_update'' hook in the Timsheet model as follows:

#timesheet.rb
class Timesheet < ActiveRecord::Base
  accepts_nested_attributes_for :activities, allow_destroy: true
  after_update :check_an_activity_present

  private
    def check_an_activity_present
      raise "You should have at least ONE activity present" if
activities.empty?
    end
end

An I put the update_attributes in the begin/rescue block in the controller:
#timesheets_controller.rb
class TimesheetsController < ApplicationController
def update
    begin
      @timesheet = current_user.timesheets.find(params[:id])
      if @timesheet.update_attributes(params[:timesheet])
        flash[:success] = ''Timesheet updated sucessfully''
        redirect_to @timesheet
      else
        load_entries
        render ''edit''
      end
    rescue Exception => e
      flash.now[:error] = e.message
      @entries = @timesheet.time_entries
      render ''edit''
    end

private
  def load_entries
      @entries = @timesheet.build_and_sort_time_entries
    end
  end
end

The problem is that the activity with corresponding time entries collection
is not destroyed even if I added a new activity with corresponding time
entries. So after the update executed, I have 2 activities saved with
corresponding time entries instad of having just the ONLY one, entered just
after the destroying the previous one. Any idea? Thank you.

--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit