Jonathan Clark
Jonathan Clark

Reputation: 20538

Check if a user object is found before destroy

I am trying to build a Rails 3.2 app and I have just a quick question when doing destroy. First I make a find to find the user I need to delete but I do not want to make destroy if it is not found.

This is my code and I feel something is missing on line 3 (if @user):

@user = User.find(params[:user_id])

 if @user
  @user.destroy
 else
  "User not found"
 end

Upvotes: 1

Views: 1286

Answers (3)

Iuri G.
Iuri G.

Reputation: 10630

you can also do this with try:

if User.find_by_id(params[:user_id]).try(:destroy)
  "User found and destroyed"
else
  "User not found or was not successfully destroyed"
end

Upvotes: 3

Anthony Alberto
Anthony Alberto

Reputation: 10395

If the user is not found, you'd get an exception

If you don't want it, do :

@user = User.find_by_id(params[:user_id])

Then your test is correct

Upvotes: 0

apneadiving
apneadiving

Reputation: 115531

Your code will not work and will raise an exception, you should do:

 @user = User.find_by_id(params[:user_id])

 if @user
   @user.destroy! #methods with bang raise an exception, I advise you to use them
   #no flash msg?
 else
   flash[:error] = "User not found"
 end

Upvotes: 2

Related Questions