Differences between Rails new, build, create, and save Methods

Source: Internet
Author: User
Document directory
  • Overview:
  • Example

Original article: http://rubyer.me/blog/262

 

New, build, and create are often used when inserting records into a database. These three methods are easy to confuse. Let's take a look at the notes:

Overview:

Save: In rails, save is actually create_or_update, creating or modifying records! Not necessarily new. Remember
New: only create an object in the memory, and call the save method to operate the database.
Create = new + Execute SQL.
Build: It is basically the same as new. It is used for one-to-multiple scenarios. For more information, see the example.
! : New !, Create !, Build! The difference with new, create, and build is that! The method will execute validate. If the verification fails, it will throw the exception.
Save is the instance method, while create, build, and new are the class methods of the model class.

Example

Set: the relationship between Article and Comment is one-to-multiple.

@ Article = Article. new (params [: article]) @ article. save

After new, you must call save to operate the database.

Note Article. build (params [: article]) reports an error. build cannot be used like this.

@ Article = Article. create (params [: article])

A record is inserted directly into the database.

@ Comment = @ article. comments. build

Similar to the new method, some people say that build will automatically set the foreign key value. In fact, I found that both build and new can set foreign keys.

If you are dealing with a "has_one" one-to-one relationship, write as follows:

@ Profile = @ user. build_profile

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.