What creates! mean in rails?

What does this do in Rails?

create! do |user| #initialise user end 

I decided that it creates user objects and stores it in the database. How does this differ from the simple expression user.new(...) and user.save() ?

+7
source share
3 answers

In a nutshell:

  • create! throws an exception, and create returns an object (an unsaved object if it fails validation).
  • save! causes an error, and save returns true / false .
  • save does not accept attributes, create .

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

+19
source

When failed to create a record, create! throws an exception, new and then save (or just create without an exclamation point) exit silently.

+3
source

create accepts attributes, so using a block here is somewhat unusual. The code you mentioned performs initialization in the block that is passed to create! It basically coincides with new , followed by initialization, and then a save!

There are many options for saving, saving !, creating, terminating !, updating, updating !, etc. there are also variations in terms of validations and backlinks

See API for more details: (this 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

-3
source

Source: https://habr.com/ru/post/901183/


All Articles