views:

143

answers:

3

I changed my show controller to find records by their permalink rather than their id (for SEO juiciness).

def show
  @project = Project.find_by_permalink(params[:id])
end

But, if I type in localhost:3000/projects/foo (and there is not a project with a foo permalink) I get a 500 server error instead of a 404 not found.

Why is this, and how can I fix it?

A: 

I assume are getting a 500 error because your show action is trying to reference attributes of @project when the find is returning nil

You need to check to make sure @projects has some data and render a 404 by hand otherwise. On my site I render a custom action called 'error' in a similar situation:

render :action => 'error', :status => 404 if @projects.blank?

If @projects exists, then the show action renders as normal.

Michael Sepcot
A: 

Or you can raise a 404 exception.

dylanfm
+6  A: 

This might be a 2.3 addition, but you can just use an exclaimation point after a dynamic finder like this:

def show
  @project = Project.find_by_permalink!(params[:id])
end

If nothing is found a ActiveRecord::RecordNotFound exception is raised.

Sam C