I’ve noticed that some methods in rails use the ! operator to raise an exception if invalid. For example, User.create!
Why and when would I want to use something like this?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
ActiveRecord will roll back a transaction if an exception is thrown while a transaction is active.
So the methods that throw exceptions are nice to ensure the database doesn’t commit a transaction when an exceptional condition occurs. When you can “handle” the problem yourself — or, if it isn’t actually a problem — then you can use the variant without the
!, check the return value for error conditions, and handle them yourself.For something specific like
User.create:User.createmethod to determine if a user-supplied username is not yet picked and provide a prompt for the user to select another name, if it is already in use.User.create!method when finally submitting the request, so that your integrity checks can fail the create and rollback the transaction in case the user attempts bypassing your friendly name check.