Reputation: 6639
Rails 4.1 Ruby 2 Windows 8.1
CarrierWave does not clean up empty directories. I am trying to get around this by doing the following in my model.
agent.rb:
after_destroy :remove_id_directory
def remove_id_directory
if @agent.avatar
folder_path = File.join(Cw_storage_folder, 'agent', 'avatar', @agent.id)
FileUtils.rm_rf(folder_path)
end
end
From agents_controller.rb
def destroy
@agent.destroy
respond_to do |format|
format.html { redirect_to agent_url }
format.json { head :no_content }
end
end
When I delete a record, I get the following error message:
undefined method `avatar' for nil:NilClass
and it points to the first line in the remove_id_directory:
if @agent.avatar
And the record was not deleted from the DB. If I remove this method and the after_destroy call, then the images are deleted, the record is deleted from the DB, but the folder stays there. Any ideas?
This works:
after_destroy :remove_cw_id_directory
def remove_cw_id_directory
FileUtils.rm_rf(File.join(Cw_storage_folder, 'agent', 'agent', self.id.to_s)) if self.avatar
end
Upvotes: 2
Views: 754
Reputation: 4147
Your problem is that you don't instantiate any @agent
variable on your agent model. If you want to get to the record attributes, you need to use self
instead.
So change your remove_id_directory
method to look something like this:
def remove_id_directory
FileUtils.rm_rf(File.join(Cw_storage_folder, 'agent', 'avatar', self.id)) if self.avatar
end
Upvotes: 1