When navigating to: http://localhost:3000/users/12
Whats a good way of avoiding the error: "Couldn't find User with
ID=12", which happens when i try to display a page of user_id 12 that
doesnt exist in the database.
Instead of showing the error. id like to show a page that says: "This
user does not exist"
Someone suggested using rescue_from. Is this the best solution for
this? Or are there better alternative approaches?
def show
@user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to users_path, :alert => "This user does not exists"
end
Ugis_Ozols
(Ugis Ozols)
September 5, 2010, 11:28am
3
One of the solutions would be to use redirect_to and flash[:notice]
like:
@user = User.find(1)
unless @user
flash[:notice] = "can't find user with given id"
redirect_to users_path
end
I won't say it's the best but it's still a solution
Yes but, it will never reach "unless." The system fails after @user =
User.find(1) since Active Record is trying to find a record that does
not exists
@user = User.find(1) if User.exists?(1)
I don't like doing two lookups for one record, but it works
What about
@user = User.find(:first, :conditions => {:id => 1})
if (@user )
blah, blah, blah
end
It's longer to type, but returns nil if the user doesn't exist.
rab
(Rob Biedenharn)
September 5, 2010, 1:42pm
7
Ugis almost has it. Try this
@user = User.find_by_id(1)
unless @user
flash[:notice] = "can't find user with given id"
redirect_to users_path
end
ActiveRecord::Base#find_by_id is a dynamic finder that will work just like the line Simon has above--nil if there is no record found.
-Rob
Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/
So this would be the convention right? not by using rescue_from. Is
this right?
Hi Paul. but wouldnt that redirect to users_path on any activerecord
not found event?
Ugis_Ozols
(Ugis Ozols)
September 5, 2010, 6:04pm
11
Good call on that find_by_id. Noted to myself
nope, only within the action.