Reputation: 1181
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()
?
Upvotes: 14
Views: 25656
Reputation: 13433
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).
Upvotes: 34
Reputation: 33732
create
takes attributes , so using a block here is somewhat unusual.
The code you mention is doing the initialization in a block that is passed to create!
It is in principal the same as new
followed by the initialization and then a save!
There are many variations save, save!, create, ceate!, update, update!, etc., there are also variations in terms of validations, and call-backs
For details please check the API: (it is discussed in the first link)
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
http://apidock.com/rails/ActiveRecord/Base
http://m.onkey.org/active-record-query-interface
Upvotes: -2
Reputation: 12215
When failed to create record, create!
throws an exception, new
and then save
(or just create
without exclamation mark) exit silently.
Upvotes: 4