Yunus Hatipoglu Yunus Hatipoglu - 6 months ago 16
Ruby Question

When written user_id on address bar does not exist, redirect root_url on Rails

When I log in to the system, on address bar, I see http://localhost:3000/admins/15, but when I write

43214321
instead of
15
, I get the following error:


Couldn't find Patient with 'id'=43214321 .


This is my code:

def show
@admin = Admin.find(params[:id].to_i)
conversations = @admin.conversations
@patient_conversations = conversations
.where.not(:patient_id => nil)
.joins(:messages)
.group("conversations.id")
.order("max(messages.created_at) DESC")
@doctor_conversations = conversations
.where(:patient_id => nil)
.where(:agency_id => nil)
.joins(:messages)
.group("conversations.id")
.order("max(messages.created_at) DESC")
@agency_conversations = conversations
.where(:patient_id => nil)
.where.not(:agency_id => nil)
.joins(:messages)
.group("conversations.id")
.order("max(messages.created_at) DESC")
end


How can I redirect to
root_url
if the record doesn't exist?

Answer

find will raise an ActiveRecord::RecordNotFound exception if the record doesn't exist. You can rescue that exception and redirect like this:

def show
  @admin = Admin.find(params[:id])
rescue ActiveRecord::RecordNotFound
  redirect_to root_url
end
Comments