According to save bang your head, active record will drive you mad, we should avoid using save!
and rescue
idiom for exceptional situations. Given that, say a model needs to @post.mark_rejected
.
If the code in mark_rejected
fails due to one of the below problems, should an exception be thrown? :
If we do not throw an exception, then:
mark_rejected
and do it's thingrescue
clause in the controller action, thus the exception bubbles up to (..wherever..) and will probably show up as some (500 HTTP?) errorExample code:
def mark_rejected ... save! end
or
def mark_rejected ... save end
save is an “Instance Method”, it returns either true or false depending on whether the object was saved successfully to the database or not. If the model is new, a record gets created in the database, otherwise the existing record gets updated.
Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The new method will return a new object while create will return the object and save it to the database. A call to user. save will commit the record to the database.
The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.
New instantiates a new Model instance, but it is not saved until the save method is called. Create does the same as new, but also saves it to the database. Sometimes you want to do stuff before saving something to the database, sometimes you just want to create and save it straight away.
save!
will raise an error if not successful.
save
will return boolean value like true or false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With