Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does create! mean in rails?

What does this do in Rails?

create! do |user| 
  #initialise user 
end

I figured it creates a user objects and saves it to the database. How is it different from just saying user.new(...) and user.save()?

like image 662
Aswath Krishnan Avatar asked Nov 10 '11 07:11

Aswath Krishnan


People also ask

What is 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.

What's the difference between new and create `?

5.1 CreateThe new method will return a new object while create will return the object and save it to the database.


1 Answers

In a nutshell:

  • create! raises an exception while create returns the object (unsaved object if it does not pass validations).
  • save! raises an error while save returns true/false.
  • save does not take attributes, create does.

new does not save. new is similar to build in ActiveRecord context. create saves to the database and returns true or false depending on model validations. create! saves to the database but raises an exception if there are errors in model validations (or any other error).

like image 130
Aditya Sanghi Avatar answered Sep 18 '22 23:09

Aditya Sanghi