Rails controller create action difference between Model.new and Model.create

我只是一个虾纸丫 提交于 2019-12-03 06:17:13

Model.new

The following instantiate and initialize a Post model given the params:

@post = Post.new(post_params)

You have to run save in order to persist your instance in the database:

@post.save

Model.create

The following instantiate, initialize and save in the database a Post model given the params:

@post = Post.create(post_params)

You don't need to run the save command, it is built in already.

More informations on new here

More informations on create here

The Model.new method creates a nil model instance and the Model.create method additionally tries to save it to the database directly.

Model.create method creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

object = Model.create does not need any object.save method to save the values in database.


In Model.new method, new objects can be instantiated as either empty (pass no construction parameter)

In Model.new(params[:params]) pre-set with attributes but not yet saved in DB(pass a hash with key names matching the associated table column names).

After object = Model.new, we need to save the object by object.save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!