Skip to content

Instantly share code, notes, and snippets.

@ecordell
Created July 22, 2011 08:13
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 ecordell/1099069 to your computer and use it in GitHub Desktop.
Save ecordell/1099069 to your computer and use it in GitHub Desktop.
class ImagesController < ApplicationController
# GET /images
# GET /images.json
def index
@imageable = find_imageable
@images = @imageable.images
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @images }
end
end
# GET /images/1
# GET /images/1.json
def show
@image = Image.find(params[:id])
@imageable = find_imageable
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @image }
end
end
# GET /images/new
# GET /images/new.json
def new
@image = Image.new
@imageable = find_imageable
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @image }
end
end
# GET /images/1/edit
def edit
@image = Image.find(params[:id])
@imageable = find_imageable
end
# POST /images
# POST /images.json
def create
@imageable = find_imageable
@image = @imageable.images.build(params[:image])
respond_to do |format|
if @image.save
format.html { redirect_to([@imageable, @image], :notice => 'Image was successfully created.') }
format.json { render :json => @image, :status => :created, :location => @image }
else
format.html { render :action => "new" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
end
end
end
# PUT /images/1
# PUT /images/1.json
def update
@image = Image.find(params[:id])
@imageable = find_imageable
respond_to do |format|
if @image.update_attributes(params[:image])
format.html { redirect_to([@imageable, @image], :notice => 'Image was successfully updated.') }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /images/1
# DELETE /images/1.json
def destroy
@image = Image.find(params[:id])
@image.destroy
@imageable = find_imageable
respond_to do |format|
format.html { redirect_to(polymorphic_path([@imageable, :images])) }
format.json { head :ok }
end
end
private
def find_imageable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment