Find the project by permanent link, 404 if not found

I changed my show controller to find entries by their permalink, and not by their identifier (for SEO juiciness).

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

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

Why is this and how can I fix it?

+3
source share
3 answers

This may be appendix 2.3, but you can simply use the exclamation point after a dynamic search as follows:

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

If nothing is found, an exception is thrown ActiveRecord::RecordNotFound.

+7
source

500, show @project, find nil

, @projects 404 . "" :

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

@projects , show .

0

Or you can throw a 404 exception.

0
source

Source: https://habr.com/ru/post/1705306/


All Articles