Forum: Ruby on Rails destroying very large object

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
9e7f68f8cf444a3a919a247e562bc464?d=identicon&s=25 Josh (Guest)
on 2007-04-19 21:20
(Received via mailing list)
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?



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

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

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

6ef8cb7cd7cd58077f0b57e4fa49a969?d=identicon&s=25 Brian Hogan (Guest)
on 2007-04-19 22:43
(Received via mailing list)
Look at the api for active_record::base.  There are some methods you can
for mass-deletes. You might use an after_delete callback and issue your
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

  def delete_related_records
     ids = self.workout_data.collect{|w|}   (gets all the ids)

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.
5c19f2d52879a1e10670c7334ba4c7e3?d=identicon&s=25 Lugovoi Nikolai (Guest)
on 2007-04-19 23:07
(Received via mailing list)
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 =  ? )",])
  WorkoutFile.delete_all([" workout_id =  ?",])

2007/4/19, Josh <>:
This topic is locked and can not be replied to.