Antoine
Antoine

Reputation: 1812

Raise an exception when no record deleted

I'm implementing a backend for an application in which users can post content. A user can delete its content anytime, but deleting another's content is forbidden.

I have a code portion that looks like the following:

Content.where(content_id: id, user_id: current_user.id).delete_all

Is there a way to make it raise an exception if no records were deleted?

I'm also using devise for handling the sign-up and authentication process. Does devise provide a way to do this check more elegantly?

Upvotes: 0

Views: 388

Answers (2)

usha
usha

Reputation: 29349

How about this?

contents = Content.where(content_id: id, user_id: current_user.id)
if contents.empty?
  raise StandardError.new("No Content") #or your custom exception
else
  contents.delete_all
end

Upvotes: 0

Mori
Mori

Reputation: 27779

delete_count = Content.where(content_id: id, user_id: current_user.id).delete_all
raise MyException if delete_count.zero?

Upvotes: 2

Related Questions