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

I go through a few Rails 3 and 4 manuals and stumble upon something that I would like:

What is the difference between Model.new and Model.create regarding the Create action. I thought you were using the create method in the controller to save, for example. @post = Post.create(params[:post]) , but it looks like I'm wrong. Any insight is greatly appreciated.

Create an action using Post.new

 def new @post = Post.new end def create @post = Post.new(post_params) @post.save redirect_to post_path(@post) end def post_params params.require(:post).permit(:title, :body) end 

Create an action using the Post.create command

 def new @post = Post.new end def create @post = Post.create(post_params) @post.save redirect_to post_path(@post) end def post_params params.require(:post).permit(:title, :body) end 

I have two questions

  • Is this due to a change in Rails 4?
  • Is it wrong to use @post = Post.create(post_params) ?
+8
ruby-on-rails ruby-on-rails-4
source share
2 answers

Model.new

The following instance and initialization of the Post model specified by the parameters:

 @post = Post.new(post_params) 

You need to run save to save your instance in the database:

 @post.save 

Model.create

The following instance initializes and stores the Post model specified by the parameters in the database:

 @post = Post.create(post_params) 

You do not need to run the save command, it is already built-in.

Additional information about new here

Read more about create here.

+22
source share

The Model.new method creates an instance of the nil model, and the Model.create method further attempts to store it directly in the database.

Model.create method creates an object (or several objects) and stores it in the database if validations pass. The resulting object returns whether the object was successfully stored in the database or not.

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


In the Model.new method Model.new new objects can be created as empty (do not pass the constructive parameter)

In Model.new(params[:params]) pre-configured with attributes, but not yet stored in the database (pass a hash with the key names corresponding to the column names of the linked tables).

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

0
source share

All Articles