Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?
like image 469
Wasabi Developer Avatar asked Jul 31 '13 07:07

Wasabi Developer


People also ask

What is the difference between new and create in Rails?

5.1 CreateThe new method will return a new object while create will return the object and save it to the database. A call to user. save will commit the record to the database.

What is action controller Rails?

Action Controller is the C in MVC. After the router has determined which controller to use for a request, the controller is responsible for making sense of the request and producing the appropriate output.

What decide which controller receives which request?

When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.

What is the main benefit that a class gets by inheriting from application controller?

By default, only the ApplicationController in a Rails application inherits from ActionController::Base . All other controllers inherit from ApplicationController. This gives you one class to configure things such as request forgery protection and filtering of sensitive request parameters.


1 Answers

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

like image 67
Pierre-Louis Gottfrois Avatar answered Sep 27 '22 23:09

Pierre-Louis Gottfrois