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.
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
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
@post = Post.create(post_params)
?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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With