destroying very large object

The situation is:

Workout has_many WorkoutFiles, :dependant => :destroy WorkoutFile has_many WorkoutData, :dependant => :destroy

There's a lot of workout data -- several thousand records per file

Workout#destroy takes a very long time (20-30 seconds) because it has to destroy so many WorkoutData records from the DB.

I tried the following solution: First, I dropped the dependant option on the Workout Class.

Then, destroy the workout, render the new page, and afterwards destroy the files (and the dependant data). This however doesn't work, it chugs along destroying the data before it updates the page.

How do I get around this?

Thanx!!!

--Code--

  def destroy     workout = Workout.find(params[:id])     workoutFiles = workout.workout_files ##get the workout files     workout.destroy ##destroy the workout     @user = User.find(current_user)     @workouts = @user.workouts     @workouts_title = "All Workouts"

#render some updates     render :update do |page|       page.replace_html 'contentBody', :partial => 'workout/workout_body'       page.replace_html 'info_bar', :partial => 'workout/ workout_left_bar' if params[:left]       page.replace_html 'calendar', :partial => 'calendar/calendar'     end

#destroy the files after the pages are updated     workoutFiles.collect{|w| w.destroy}                       ##(20-30 seconds of destroying here)

  end

Look at the api for active_record::base. There are some methods you can use for mass-deletes. You might use an after_delete callback and issue your own delete statement so you can avoid invoking all those callbacks.

in the workout_file.rb class, try this

has_many :workout_data

after_destroy :delete_related_records

protected def delete_related_records ids = self.workout_data.collect{|w| w.id} (gets all the ids) WorkoutData.delete(ids) end

That should be faster. You may need to move that up a level to the workout and have it collect all the related records… but this is the general idea.

You could use mass deletes without loading associated objects on destroy, with smth like:

Workout.transaction do   WorkoutData.delete_all([" workout_file_id in (select id from workout_files where workout_id = ? )", workout.id])   WorkoutFile.delete_all([" workout_id = ?", workout.id])   workout.destroy end