Effectively using rescue_from
This article is left here for historical purposes, please read the comments carefully after you’ve read the article.
Even though Ryan Daigle already covered it in his usual timely fashion, I’d like to share some real life examples of how we use the relatively new rescue_from functionality.
Because I usually prefer methods that raise exceptions instead of returning a boolean, like, say, save! instead of just save, I thought it would be nice if I could deal with some common exceptions on a higher level. This lead me to write a Rails patch based on the exception_handler plugin, which I previously used in some projects.
class PostsController < ApplicationController
def create
@post = Post.create!(params[:post])
rescue ActiveRecord::RecordInvalid
render :action => :new
end
def update
@post = Post.find(params[:id])
@post.update_attributes!(params[:post])
rescue ActiveRecord::RecordInvalid
render :action => :edit
end
end
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordInvalid do |exception|
render :action => (exception.record.new_record? ? :new : :edit)
end
end
class PostsController < ApplicationController
def create
@post = Post.create!(params[:post])
end
def update
@post = Post.find(params[:id])
@post.update_attributes!(params[:post])
end
end
And it just works.
At Fingertips we design and develop Web, iPhone, iPad and Mac OS X apps.
Find out how to hire us…




Subscribe to our mailing list — Follow us on Twitter — Grab our feed — Fork our code on GitHub