[RUBY] [Rails] I studied the difference between new method, save method, build method and create method.

I'm a beginner with "super" who is struggling with Rails every day. Share for organizing your own knowledge.

Isn't there a lot of methods for creating objects?

I didn't notice this fact when I was scanning the text, but the other day "Oh, if you think it's a new method, do you use the create method here ... If you think about it, there's a build ... What ?! " I was in such a state, so I decided to investigate it myself. It's a short article, but please stay with me until the end. image.png

About new method & save method

First, let's start with the basic usage of the new method. By the way, I am writing on the assumption that I will post with the Book model.

ruby:books_controller:rb


def new
  @book = Book.new
end

I created an empty instance of the Book class in Book.new and assigned it to the @book instance variable. "Everyone knows this" I used to think so, but there was a way to specify the argument with the new method. Here is it

ruby:books_controller:rb


def new
  @book = Book.new(title: "Rashomon", author:"Ryunosuke Akutagawa")
#The title is "Rashomon" and the author is "Ryunosuke Akutagawa".
end

If you post a new book with this, no matter what characters you enter in the input field, you will not be able to register other than Rashomon (laugh) The new method didn't just pass an empty instance. I'm sorry for those who knew it.

After the new method, use the save method in the create action to save the data. Here is it

ruby:books_controller:rb


def create
  @book = Book.new(book_params)
  @book.save
end

Finally, I was able to newly register in the Book database. In the case of the save method, it can be saved in the database together with the new method.

About the create method

This is where the rumored create method comes in. The steps saved using the new method and save method described above can be completed in just one line with the create method.

What does that mean?

ruby:books_controller:rb


def create
  Book.create(title: "Rashomon", author:"Ryunosuke Akutagawa")
end

With this alone, I was able to save it in the database. Not only can you save the data, but you can also instantiate the model at the same time. Mecha easy. Easy.

Basic syntax


Model name.create(Column name: "value")

Again, the create method is a method that is doing new and save at the same time.

Then why not just use the create method? It seems that a shallow idea will come up, but it is not so sweet.

How to use properly

If you want to do something with the created instance, you can't use the create method, so you'll have to write a new method and a save method. Specifically

  1. When you want to create a conditional branch using if
  2. When you want to get an error message with render And so on, which will be explained below.

❶ Conditional branching using if

users_controller.rb


def create
  @user = User.new(user_params) #Create an instance variable
  if @user.save
    redirect_to @user, notice: 'User creation completed'
  else
    render :new #Render destination when save could not be done
  end
end

In this way, when conditional branching occurs, such as using instance variables to divide into success patterns and failure patterns, the new method and save method should be used.

❷ I want to issue an error message with render

For example, on the screen for making a new post (new action), the validation check works and the post cannot be made. At that time, if an error message appears above the post column, it is very easy to understand. I will explain in detail.

ruby:books_controller:rb


def new
  @book = Book.new
end

def create
  @book = Book.new(params[:id])
  if  @book.save
      redirect_to book_path(@book.id)
  else
      render 'layouts/errors'
  end
end

ruby:views/books/new.html.erb


<h1>New Book</h1>
<%= render 'layouts/errors', obj: @book %>
#abridgement

ruby:layouts/_errors.html.erb


<% if obj.errors.any? %>  #to obj@Substitute book
  <div id="error_explanation">
    <h3><%= pluralize(obj.errors.count, "error") %> prohibited this obj from being saved:</h3>

    <ul>
    <% obj.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  </div>
<% end %>

As mentioned above, even when using an instance variable containing the new method and issuing an error message, it is not possible with the create method alone. I often have to think about it ...

About the build method

It's finally the last method. However, I think it is the least important. In current rails, the new and build methods work almost the same. In older versions of rails, the difference was whether or not a foreign key was automatically added when the association was made, but now both the new method and the build method are set with a foreign key. Depending on the workplace, there are cases where build is recommended in specific situations, but if not, it will not be a problem to unify it into a new method.

in conclusion

This time too, I learned a lot. The more you dig deeper, the more you will discover new things, even if you think, "I know this well." I will continue to devote myself to studying.

Recommended Posts

[Rails] I studied the difference between new method, save method, build method and create method.
[Rails] Difference between create method and new + save method
[Rails / ActiveRecord] About the difference between create and create!
[Rails] I learned about the difference between resources and resources
[Rails] I investigated the difference between redirect_to and render.
Difference between i ++ and ++ i
[Ruby] I thought about the difference between each_with_index and each.with_index
Difference between new and create in Rais action controller
Rails: Difference between resources and resources
[Rails] What is the difference between bundle install and bundle update?
What is the difference between an action and an instance method?
Let's override the difference between == (identity) and equals method (equivalence)
Difference between instance method and class method
Difference between render method and redirect_to
Difference between == operator and equals method
Difference between == operator and eqals method
[Rails] Difference between find and find_by
Understand the difference between each_with_index and each.with_index
Now in the third year, the misunderstanding that I noticed is the difference between the equals method and ==
[rails] Difference between redirect_to and render
Install Rails in the development environment and create a new application
Easy to understand the difference between Ruby instance method and class method.
About the difference between irb and pry
I studied the State pattern and the Strategy pattern
[Rails] Difference between redirect_to and render [Beginner]
[Java] Understand the difference between List and Set
[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
I specified the version and rails new, but for some reason the latest version is included ~
About the relationship between Rails credentials.yml.enc and master.key (undefined method `[]'for nil: NilClass (NoMethodError))
What is the difference between a class and a struct? ?? ??
What is the difference between System Spec and Feature Spec?
Ethereum Transaction Sending Method Difference between send and sendAsync
About the difference between classes and instances in Ruby
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 ""
[Java beginner] Difference between length and length () ~ I don't know ~
Difference between vh and%
[Rails] I don't want to get lost anymore. Create new models, tables, controllers and views.
I will explain the difference between Android application development and iOS application development from the perspective of iOS engineers
Regarding the difference between Java array and ArrayList, I compared and corresponded methods with similar functions.
[Rails] I tried using the button_to method for the first time
About the difference between "(double quotation)" and "single quotation" in Ruby
I want to call a method and count the number
I want to create a form to select the [Rails] category
What happens when I do new => build => save! In ActiveRecord
[Ruby] About the difference between 2 dots and 3 dots of range object.
[Java] Check the difference between orElse and orElseGet with IntStream
[Rails] Create new files required for the application at once
The difference between programming with Ruby classes and programming without it
[Ruby] Difference between each method and for statement. The elements are taken out one by one and processed.
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