Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get model or 404 on Rails

Is it possible to use a function as get_by_id_or_404 on rails. For exemple, in my controller i use :

@destination = Destination.find_by_id(params[:id])

if the id isn't set or the destination not found, how can I ask Rails to redirect to a 404 page?

Thank you!

like image 621
Sebastien Avatar asked Oct 07 '11 10:10

Sebastien


3 Answers

In production mode, Rails automatically rescues the ActiveRecord::RecordNotFound exception by rendering the 404 error page.

Simply use the bang version of the finder that raises ActiveRecord::RecordNotFound when no result is found.

@destination = Destination.find_by_id!(params[:id])

However, in your case there's no reason to use the find_by method. Simply fallback to find.

@destination = Destination.find(params[:id])
like image 153
Simone Carletti Avatar answered Oct 11 '22 13:10

Simone Carletti


This is from the guide:

You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like Client.find_by_name!("Ryan")

When this happens, Rails will render the 404 page for you. Also, simply use find as a shortcut for find_by_id:

@destination = Destination.find!(params[:id])
like image 37
rdvdijk Avatar answered Oct 11 '22 14:10

rdvdijk


I think in production, it will raise the error and display the 404 or 500.

like image 24
damienbrz Avatar answered Oct 11 '22 14:10

damienbrz