11

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)?
Wasabi Developer
  • 3,523
  • 6
  • 36
  • 60
  • possible duplicate of [Rails new vs create](http://stackoverflow.com/questions/2472393/rails-new-vs-create) – Amadan Jul 31 '13 at 07:04
  • 1
    Thanks for the reference Amadan. Is Rails REST implement of `GET` and `POST` the same as the controller actions `new` and `create`? I'm trying to clarify REST vs controller actions vs controller methods. – Wasabi Developer Jul 31 '13 at 07:15
  • Sorry, I should have clarified; the answer by Justin Ethier specifically refers to ActiveRecord methods. – Amadan Jul 31 '13 at 07:17

2 Answers2

24

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

Pierre-Louis Gottfrois
  • 17,561
  • 8
  • 47
  • 71
0

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

Debadatt
  • 5,935
  • 4
  • 27
  • 40