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!
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])
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])
I think in production, it will raise the error and display the 404 or 500.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With