[RUBY] [Rails / ActiveRecord] About the difference between create and create!

Overview

About the ActiveRecord method create that creates a new record. I learned about the difference between create and create!, so I will explain it.


Conclusion: Whether to raise an exception

What is the difference with and without ! ? Conclusion "Whether to raise an exception".

However, it is difficult to understand the "exception". To explain the difference that actually occurs, what changes with or without ! is "Is that red screen appearing?" When processing fails.


In the case of create!

If you set create!, If you get caught in validation, an ActiveRecord :: RecordInvalid exception will occur as shown below, and the familiar screen will be displayed.

domo

Let's follow the actual operation.

The code used this time is as follows (* The description of create action is not recommended).

① Routing

app/config/routes.rb


Rails.application.routes.draw do
  root to: 'comments#index'
  resources :comments, only: [:create]
end
  1. Submit an empty value in the form of index.html.erb
  2. Request comments # create

② Execute comments # create action

app/controllers/comments_controller.rb


class CommentsController < ApplicationController

  def index
    @comments = Comment.all.order("created_at DESC")
    @comment = Comment.new
  end

  def create
    #Writing this create action is deprecated.
    @comment = Comment.create!(comment_params)
    redirect_to root_path
  end

  private

  def comment_params
    params.require(:comment).permit(:text)
  end
end
  1. Load the ActiveRecord method create (new + save)
  2. Get parameters with comment_params (text column value is empty)
  3. Validation check in the save part of create

③ Validation check with Comment model

app/models/comment.rb


class Comment < ApplicationRecord
  validates :text, presence: true
end
  1. It gets stuck in the validation set in the text column
  2. Exception occurs because it cannot be saved
  3. That red screen is displayed

✔ GIF that follows the above flow

The error screen was displayed firmly.

demo


Without !

Submit the form for the create action below.

app/controllers/comments_controller.rb


def create
  @comment = Comment.create(comment_params) # !Exclude
  redirect_to root_path
end

✔ Operation in this case (GIF)

The error screen does not occur due to exception handling, and you are redirected.

demo


Summary


reference

Recommended Posts

[Rails / ActiveRecord] About the difference between create and create!
[Rails] I learned about the difference between resources and resources
About the difference between irb and pry
[Rails] Difference between create method and new + save method
Rails: Difference between resources and resources
[Rails] I studied the difference between new method, save method, build method and create method.
[Ruby] I thought about the difference between each_with_index and each.with_index
About the difference between classes and instances in Ruby
[Rails] What is the difference between redirect and render?
[Rails] I investigated the difference between redirect_to and render.
[Rails] Difference between find and find_by
Understand the difference between each_with_index and each.with_index
[rails] Difference between redirect_to and render
[Rails] What is the difference between bundle install and bundle update?
About the difference between "(double quotation)" and "single quotation" in Ruby
[Ruby] About the difference between 2 dots and 3 dots of range object.
[Rails] Difference between redirect_to and render [Beginner]
About the difference between gets and gets.chomp (other than line breaks)
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
[Java] Understand the difference between List and Set
[Rails] Difference in behavior between delegate and has_many-through in the case of one-to-one-to-many
[iOS] Understand the difference between frame and bounds
Understand the difference between abstract classes and interfaces!
What is the difference between SimpleDateFormat and DateTimeFormatter? ??
Difference between member and collection of rails routes.rb
A note about the Rails and Vue process
Difference between vh and%
Difference between i ++ and ++ i
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Find out about Rails hidden_field (create a confirmation screen and check the behavior)
What is the difference between a class and a struct? ?? ??
What is the difference between System Spec and Feature Spec?
Difference between new and create in Rais action controller
About the relationship between HTTP methods, actions and CRUD
Compare the difference between dockerfile before and after docker-slim
[JAVA] What is the difference between interface and abstract? ?? ??
What is the difference between skip and pending? [RSpec]
What is the difference between Java EE and Jakarta EE?
[Swift] UITextField taught me the difference between nil and ""
Difference between product and variant
Difference between redirect_to and render
[Java] Difference between == and equals
about the where method (rails)
Difference between puts and print
Difference between redirect_to and render
Difference between CUI and GUI
Difference between variables and instance variables
Difference between mockito-core and mockito-all
About the same and equivalent
Difference between class and instance
Difference between bundle and bundle install
Difference between ArrayList and LinkedList
Difference between render and redirect_to
Difference between List and ArrayList
Difference between .bashrc and .bash_profile
Difference between StringBuilder and StringBuffer
Difference between render and redirect_to
Difference between render and redirect_to
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
About the relationship between Rails credentials.yml.enc and master.key (undefined method `[]'for nil: NilClass (NoMethodError))
Difference between Java and JavaScript (how to find the average)