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 ~
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.
We will create new posts with this new.html.erb file.
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);
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 %>
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.
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 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.
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.
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.
Enter at least 20 characters as shown below and press send.
Nothing in particular changes.
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