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()
?
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.
5.1 CreateThe new method will return a new object while create will return the object and save it to the database.
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).
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