Twdeveloper
Twdeveloper

Reputation: 203

cannot delete or update a parent row a foreign key constraint fails rails

I have received the following error when trying to delete a value in rails "cannot delete or update a parent row a foreign key constraint fails rails"

This is perfectly acceptable to me as I don't want the user to be able to delete the value if it's associated with another value. However, what is the best way to catch the exception and then notify 'alert' the user that this value cannot be deleted?

Thank You,

TW

Upvotes: 5

Views: 4380

Answers (2)

mattforni
mattforni

Reputation: 875

There are plenty of ways to handle this gracefully. If you'd like to do a check before the destroy I recommend you take a look at this post as it shows a good example of using the before_destroy method and gives you control of the error you show. However, you can also add a rescue_from and capture the error in your controller.

Upvotes: 1

Prakash Murthy
Prakash Murthy

Reputation: 13067

*********** Mysql Error:
"Cannot delete or update a parent row: a foreign key constraint fails."

This error message is usually raised by the database(mysql) and not rails(active record), and will usually be wrapped in an active record exception like ActiveRecord::RecordNotUnique

Try the following to figure out which exception to catch:

begin
   <delete action expected to raise the above mentioned error>
rescue Exception => e
  logger.debug "#{e.class}"
end

Upvotes: 0

Related Questions