Question

I'm having issue with a youtube video being destroyed properly in a nested belongs_to has_one relationship between a sermon and its sermon video when using :dependent => :destroy.

I'm using the youtube_it gem and have a fairly vanilla setup.

The relevant bits below:

the video controller --

def destroy
  @sermon = Sermon.find(params[:sermon_id])
  @sermon_video = @sermon.sermon_video

  if SermonVideo.delete_video(@sermon_video)
    flash[:notice] = "video successfully deleted"
  else
    flash[:error] = "video unsuccessfully deleted"
  end
  redirect_to dashboard_path
end

the video model --

belongs_to :sermon

def self.yt_session
  @yt_session ||= YouTubeIt::Client.new(:username => YouTubeITConfig.username , :password => YouTubeITConfig.password , :dev_key => YouTubeITConfig.dev_key)
end

def self.delete_video(video)
  yt_session.video_delete(video.yt_video_id)
  video.destroy
    rescue
      video.destroy
end

the sermon model --

has_one :sermon_video, :dependent => :destroy

accepts_nested_attributes_for :sermon_video, :allow_destroy => true

In the above setup, all local data is removed successfully; however, the video on youtube is not.

I have tried to override the destroy action with a method in the model, but probably due a failing of my understanding, can only get either the video deleted from youtube, or the record deleted locally, never both at the same time (I posted the two variants below and their results).

This only serves to destroy the local record --

def self.destroy
  @yt_session ||= YouTubeIt::Client.new(:username => YouTubeITConfig.username , :password => YouTubeITConfig.password , :dev_key => YouTubeITConfig.dev_key)
  @yt_session.video_delete(self.yt_video_id)

  @sermon_video.destory
end

This only serves to destroy the video on youtube, but not the local resource --

def self.destroy
  @yt_session ||= YouTubeIt::Client.new(:username => YouTubeITConfig.username , :password => YouTubeITConfig.password , :dev_key => YouTubeITConfig.dev_key)
  @yt_session.video_delete(self.yt_video_id)
end

Lastly, the link I'm using to destroy the sermon, in case it helps --

<%= link_to "Delete", [@sermon.church, @sermon], :method => :delete %>

Thanks for your help, very much appreciated!

Was it helpful?

Solution

It looks as though I have just solved the issue; however, I'll leave it open for a bit in case someone has a more elegant / appropriate solution.

In the sermon video model I added --

before_destroy :kill_everything

def kill_everything
  @yt_session ||= YouTubeIt::Client.new(:username => YouTubeITConfig.username , :password => YouTubeITConfig.password , :dev_key => YouTubeITConfig.dev_key)
  @yt_session.video_delete(self.yt_video_id)
end

And the key thing, I believe, to have added in the sermon model was this --

accepts_nested_attributes_for :sermon_video, :allow_destroy => true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top