Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use `save` vs `save!` in model?

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 there is a validation problem
  • if a non-nullable-field was being assigned a null
  • if there was a connection loss to database

If we do not throw an exception, then:

  • controller action would have to check for return value of mark_rejected and do it's thing
  • we are not expecting an exception from that method call, so we do not write a rescue clause in the controller action, thus the exception bubbles up to (..wherever..) and will probably show up as some (500 HTTP?) error

Example code:

def mark_rejected   ...   save! end 

or

def mark_rejected   ...   save end 
like image 988
Zabba Avatar asked Feb 20 '11 10:02

Zabba


People also ask

What does SAVE do in Ruby on Rails?

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.

What does active record save return?

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.

What happens on Save rails?

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.

What is the difference between new and create in rails?

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.


1 Answers

save! will raise an error if not successful.

save will return boolean value like true or false.

like image 100
Selvamani Avatar answered Sep 22 '22 13:09

Selvamani