Skip to content

Instantly share code, notes, and snippets.

@nakajima

nakajima/FIRST Secret

Created June 30, 2009 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakajima/6f12ea9c7faad2c9860d to your computer and use it in GitHub Desktop.
Save nakajima/6f12ea9c7faad2c9860d to your computer and use it in GitHub Desktop.
This actually isn't the best solution. It seems like all of this logic
should instead be the concern of some sort of Photo model, which may or
may not need be an association. With that being said, here's my take...
# Your Page model
class Page < ActiveRecord::Base
# Create a callback to delete the photo file if appropriate.
# This is nice because in the case where the page is otherwise
# invalid, it won't unnecessarily delete the photo
after_save :delete_photo_file, :if => :photo_deleted?
# Setter method that gets called when you pass :clear_photo => true
# to update_attributes
def clear_photo=(clearing)
if has_photo?
@deleted_photo_path = photo_file_name
end
end
# Check for presence of deleted photo path. If set, then we can assume
# that the photo has in fact been deleted
def photo_deleted?
@deleted_photo_path
end
# Check for the presence of a photo_file_name. If set, then we can assume
# that the page has a photo.
def has_photo?
photo_file_name
end
private
# Callback method invoked by the after_save
def delete_photo_file
File.delete("#{RAILS_ROOT}/public/images/frontend/#{photo_file_name}")
self.photo_file_name = nil
save!
end
end
# Your controller action:
class PagesController < ApplicationController
def update
# First, find the appropriate page...
@page = Page.find(params[:id])
# Update the attributes
@page.update_attributes!(params[:page])
# return some sort of response
end
end
# Add this to your routes:
map.resources :pages
<%= link_to_remote "Delete this image", page_path(@page, :page => { :clear_photo => true }), :method => :put) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment