Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~

Introduction

This time is a continuation of the previous article.

Please see the previous article if you like.

Let's learn about validation this time.

Explanation of Ruby on rails for beginners ①

Explanation of Ruby on rails for beginners ② ~ Creating links ~

Explanation of Ruby on rails for beginners ③ ~ Creating a database ~

Explanation of Ruby on rails for beginners ④ ~ How to use naming convention and form_Tag ~

Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~

Create a new controller

Let's create a new controller.

This time, we'll create a posts controller to manage the posts. Execute the following code in the terminal.

rails g controller posts all

Make sure you see all your posts in the all.html.erb file.

To do this, create a file that creates a new post. Let's create a new.html.erb file inside the posts file.

image.png

We will create new posts with this new.html.erb file.

Creating a new model

Now let's create a database to manage posts. This time, we haven't created the database at all yet, so we will create it from the model.

A model is a mechanism for manipulating database information, and can also be called a class that interacts with the database.

Models are usually named in the singular, starting with a lowercase letter. Because there is only one model for table.

 rails g model post content: string

When you create a model like this, a migration file, which is a design drawing of the database, is created at the same time.

Let's run the migration file with the following code.

rails db:migrate

Let's check the created table from the database console.

rails dbconsole
.table

ar_internal_metadata schema_migrations
posts users

The posts table has been created. Let's take a look at the contents with the following code.

.schema posts

CREATE TABLE IF NOT EXISTS "posts" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "content" varchar, "string" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);

Create a post

Let's add the code to create the post to the new.html.erb file.

new.html.erb


<%= form_tag("/posts/create") do  %>  
  <textarea name="content" cols="30" rows="10"></textarea>
  <input type="submit" value="Send">
<% end %>

image.png

I am sending a post request to the URL / posts / create. The data inside the textarea is stored in params [: content] and sent.

Let's route as follows.

routes.rb


post "posts/create" => "posts#create"

It is routed to the create action of the posts controller. To store the data in the textarea in the posts table, code the posts controller as follows:

posts_controller.rb


def create
  post = Post.new(content: params[:content])
  post.save
  redirect_to("/posts/new")
end

You can now save the data in the posts table.

Fill in the textarea as shown below and press the submit button.

image.png

Let's check the database. Type the following code in the terminal.

rails dbconsole
.header on
select * from posts;

id|content|string|created_at|updated_at 1|pocomaru||2020-05-23 10:37:51.509719|2020-05-23 10:37:51.509719

In this way, we were able to store the post in the database.

Validation settings

Validation is a constraint placed on storing data in the database.

For example, when you log in to some site, you should be able to log in even if your e-mail address and password are empty.

It exists to prevent such a thing.

Validation is set on the model.

Let's actually set it.

Prevent empty posts

Consider validation to prevent empty posts.

Since it is the posts table that stores posts, this validation is done inside the Post class of the post model.

The post model is as follows by default.

post.rb


class Post < ApplicationRecord
end

Validation is written in the following format

validates: column name, {validation content}

The validation to prevent empty posts is as follows.

post.rb


class Post < ApplicationRecord
end

Validation is written in the following format

validates: column name, {validation content}

The validation to prevent empty posts is as follows.

post.rb


class Post < ApplicationRecord
    validates :content, {presence: true}
end

This prevented empty posts.

If you get stuck in validation, you will not be able to save. Also, if save is successful, True will be returned as the return value, and if save is unsuccessful, False will be returned as the return value.

Let's rewrite the posts controller as follows.

posts_controller.rb


def create
  post = Post.new(content: params[:content])
  if post.save
    redirect_to("/posts/all")
  else
    redirect_to("/posts/new")
  end

By rewriting the code in this way, if the save succeeds, it redirects to / posts / all, and if the save fails, it redirects to / posts / new.

You have now created a validation that eliminates empty posts.

Next, let's create a validation that removes more than a certain number of characters.

Prevent more than a certain number of characters

This time, let's set a validation that prevents posting of 20 characters or more.

It will be as follows.

post.rb


class Post < ApplicationRecord
    validates :content, {presence: true}
    validates :content, {length: {maximum: 20}}
end

This validates: content, {length: {maximum: 20}} part allows you to limit posts of 20 characters or more.

However, there is a problem if you just set the validation like this. When I post more than 20 characters, the textarea becomes empty.

The reason is in the posts controller. When validation is caught and redirect_to ("/ posts / new") is called, routing will perform a new action on the posts controller. Then, the instance variable cannot be sent to the new.html.erb file, and the textarea I wrote hard will be empty.

To prevent this, we use a method called render.

Rendering is a method that can be rendered, and rendering is to have the browser load the view file and render it.

You can use the render method in a view file to use a partial template that renders the common parts of multiple view files.

This time, by using it inside the controller, you can pass the created instance variable to the view file by rendering without going through the action.

Let's rewrite the posts controller as follows.

def create
  post = Post.new(content: params[:content])
  @content = params[:content]
  if post.save
    redirect_to("/posts/all")
  else
    render("posts/new")
  end
end

After storing the content of the post in @ content, I'm using render instead of redirect_to to render the new.html.erb file.

This way you can pass the instance variable @ content to new.html.erb.

To display this instance variable in the new.html.erb file, rewrite it as follows.

new.html.erb


<%= form_tag("/posts/create") do  %>  
  <textarea name="content" cols="30" rows="10"><%= @content%></textarea>
  <input type="submit" value="Send">
<% end %>

We are passing @content to the initial value of the textarea. Now you can see the value when you get stuck in validation.

Let's try it out.

image.png

Enter at least 20 characters as shown below and press send.

image.png

Nothing in particular changes.

image.png

At the end

That's all for this time.

Thank you for your relationship.

Please see the following articles if you like.

Explanation of Ruby on rails for beginners ⑦ ~ Implementation of flash ~

Recommended Posts

Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ①
Explanation of Ruby on rails for beginners ② ~ Creating links ~
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
Ruby on Rails for beginners! !! Summary of new posting functions
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
[Ruby on Rails] About bundler (for beginners)
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
Validation settings for Ruby on Rails login function
Portfolio creation Ruby on Rails
Ruby on Rails validation summary
Summary of rails validation (for myself)
Basic knowledge of Ruby on Rails
[Ruby on Rails] Confirmation page creation
[Ruby on Rails] Introduction of initial data
Let's summarize "MVC" of Ruby on Rails
Ruby on Rails model creation / deletion command
part of the syntax of ruby ​​on rails
Ruby on Rails for beginners! !! Post list / detailed display function summary
Ruby on Rails application new creation command
[Ruby on Rails] Japanese notation of errors
(2021) Ruby on Rails administrator (admin) login creation
[Ruby on rails] Implementation of like function
Beginners create portfolio in Ruby on Rails
How to build a Ruby on Rails environment using Docker (for Docker beginners)
[Ruby] Explanation for beginners of iterative processing with subscripts such as each_with_index!
A series of flow of table creation → record creation, deletion → table deletion in Ruby on Rails
Implementation of Ruby on Rails login function (Session)
[Beginner Procedure Manual 2] Ruby on Rails: Rails template creation
[Ruby on Rails] Until the introduction of RSpec
Recommendation of Service class in Ruby on Rails
[Ruby on Rails] Select2 introduction memo for Webpacker
Ruby on Rails ~ Basics of MVC and Router ~
[Ruby on Rails] A memorandum of layout templates
[Rails] Procedure for linking databases with Ruby On Rails
[Ruby on Rails] Individual display of error messages
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
Scraping for beginners (Ruby)
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
Implementation of Ruby on Rails login function (devise edition)
Docker the development environment of Ruby on Rails project
Try using the query attribute of Ruby on Rails
[Ruby on Rails] Implementation of validation that works only when the conditions are met
Ruby on rails learning record -2020.10.03
Ruby on rails learning record -2020.10.04
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
Ruby on Rails basic learning ①
[Ruby on Rails] about has_secure_password
Ruby on rails learning record-2020.10.07 ②
(For beginners) [Rails] Install Devise
Commentary on partial! --Ruby on Rails
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
Ruby on rails learning record -2020.10.06
Ruby on Rails Basic Memorandum