Created
October 22, 2009 15:59
-
-
Save skojin/216042 to your computer and use it in GitHub Desktop.
way to handle validation in controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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