Skip to content

Instantly share code, notes, and snippets.

@skojin
Created October 22, 2009 15:59
Show Gist options
  • Save skojin/216042 to your computer and use it in GitHub Desktop.
Save skojin/216042 to your computer and use it in GitHub Desktop.
way to handle validation in controller
# implement alternative way to handle form validation error, via rescue_from ActiveRecord::RecordInvalid
# use Record.create! and @record.update_attributes!
module RescueFromValidationError
# usage: rescue_from_validation_error('@user')
def rescue_from_validation_error(instance_variable_name, options = {})
rescue_from ActiveRecord::RecordInvalid, :with => :handle_validation_error
define_method(:handle_validation_error) do |e|
instance_variable_set(instance_variable_name, e.record)
respond_to do |format|
format.html { render :action => (e.record.new_record? ? options[:form] || 'new' : options[:form] || 'edit') }
end
end
end
end
rescue_from ActiveRecord::RecordInvalid, :with =>
handle_validation_error
def create
article = current_user.articles.create!(params[:article])
flash[:notice] = "..."
respond_to do |format|
format.html { redirect_to root_path }
end
end
private
def handle_validation_error(e)
@article = e.record
respond_to do |format|
format.html { render :action => (@article.new_record? ? 'new' :
'edit') }
end
end
class MyController < ApplicationController
extend RescueFromValidationError
rescue_from_validation_error('@user')
def create
@user = User.create! params[:user]
flash[:notice] = "User successfully created"
redirect_to @user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment