Rails controller create action difference between

2019-03-18 18:50发布

问题:

I'm going through a few Rails 3 and 4 tutorial and come across something I would love some insights on:

What is the difference between the Model.new and Model.create in regards to the Create action. I thought you do use the create method in the controller for saving eg. @post = Post.create(params[:post]) but it looks like I'm mistaken. Any insight is much appreciated.

Create 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 action using Post.create

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 to do with a Rails 4 change?
  • Is it bad practice to use @post = Post.create(post_params)?

回答1:

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



回答2:

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