Skip to content

Instantly share code, notes, and snippets.

@baldwindavid
Created November 17, 2009 00:47
Show Gist options
  • Save baldwindavid/236494 to your computer and use it in GitHub Desktop.
Save baldwindavid/236494 to your computer and use it in GitHub Desktop.
# Careful with to_param
class Page < ActiveRecord::Base
validates_presence_of :handle
validates_uniqueness_of :handle
validates_format_of :handle, :with => /^[a-z0-9-]+$/, :message => 'The handle can only contain lowercase letters, numbers and dashes.'
def to_param
handle
end
end
# Make sure to capture the old handle on uniqueness validation errors.
# Otherwise, submitting the form after render with the same handle will
# submit to the duplicate address (i.e. /pages/my-page/edit) and override and
# save both records with the new values
class PagesController < ApplicationController
def update
@page = Page.find(params[:id])
old_handle = @page.handle
respond_to do |format|
if @page.update_attributes(params[:page])
flash[:notice] = 'Page was successfully updated.'
format.html { redirect_to edit_page_url }
else
@page.handle = old_handle
format.html { render :action => "edit" }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment