Document directory
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