I wanted to create some service using Rails, so I started learning and decided to leave it in the article as a memorandum. This time, I learned the new posting function of the web application. Please comment if you have any misunderstandings or advice.
I created a Post model and edited my graying file in advance. I edited the migration file as follows.
class CreatePosts < ActiveRecord::Migration[5.2] def change create_table :posts do |t| #from here t.string :title t.string :body #Edit up to here t.timestamps end end end
Type a command from the terminal to reflect the creation of the table.
$ rails db:migrate == 20210104014856 CreatePosts: migrating ====================================== -- create_table(:posts) -> 0.0193s == 20210104014856 CreatePosts: migrated (0.0202s) =============================
Now that the table is created, you're ready to go.
In Rails, it is common to define the basic functions of a web application with the following action names.
|new||Create a new data creation form|
|create||Add / save data|
|index||Display a list of data|
|show||Display detailed data|
|edit||Create a data edit form|
|update||Update the data|
Create a controller in the terminal.
rails g controller posts
rails g controller controller name action name
If you add an action name as described above, it seems that the action and the routing and view corresponding to that action will be created automatically, but this time we will proceed without giving an action name to grasp the flow. I will continue.
Now let's define a new action for the controller we created.
class PostsController < ApplicationController #from here def new end #Add up to here end
Next, we will set the routing in app/config/routes.rb.
Rails.application.routes.draw do #from here get 'posts/new' => 'posts#new' #Add up to here end
In this description, it means "When you access the path of posts/new by GET of HTTP method, the new action of posts controller is called."
Create a view file to display to the user the next time the post controller's new action is called. Since the posts folder was created in app/views when the controller was created, create a new.html.rb file directly under it.
Open the created file and describe the page name so that it is easy to understand.
Now when you access the/posts/new path from your browser, you'll see the view file you just created.
To create a new post, you need to pass an empty model to the form. in the new action of the posts controller
class PostsController < ApplicationController def new #from here @post = Post.new #Add up to here end end
If you write like, an empty model will be created and assigned to the instance variable @post so that it can be used in view.
Next, we will create the posting form required for new posting. Rails has a "helper method" that summarizes the common processing called from view, and this time we will use this one form_for helper.
<h1>Post form</h1> #from here <%= form_for(@post, url: '/posts') do |f| %> <h3>title</h3> <%= f.text_field :title %> <h3>Text</h3> <%= f.text_area :body %> <%= f.submit 'Post' %> <% end %> #Add up to here
By assigning an empty model to the first argument of the form_for helper and specifying the instance variable, the form and the Post model are associated. In the second argument, specify the destination path. This time, I will write the save process to the database with the create action, so I specified the path to that point.
Up to this point, you can implement the form input, and the post form has been added.
First, set the routing.
Rails.application.routes.draw do get 'posts/new' => 'posts#new' #from here post 'posts' => 'posts#create' #Add up to here end
If you want to submit the form data to the controller, use the POST method. Now you can set the posts controller to call the create action when you submit the form.
Next, we will implement the create action that saves the data. Write this under the new action:
def create post = Post.new(post_params) post.save redirect_to '/posts/new' end private def post_params params.require(:post).permit(:title, :body) end
When submitting data from a form, there is a security problem that an unexpected value may be changed due to a malicious request when submitting data called "mass assignment vulnerability". Rails provides a mechanism called "strong parameters" to prevent this. The code below from private is that.
Strong parameters are responsible for receiving the data submitted from the form and passing it to create and update. It also has the role of preventing unauthorized access. The object name of the data is specified by require, and the key name of the value is specified by permit.
Let's look at the contents of the create action one by one.
post = Post.new(post_params)
In, we create an instance of the post model, receive the value submitted from the form from the strong parameter as an argument, and assign it to the local variable post.
Then use the save method to save the data in the DB.
Finally, specify the page to return to after the process of saving to the DB is completed. This time, it is specified to return to the post form page when the save process is completed.
This completes the implementation of the new posting function.
I will actually post it and check it with MySQL.
mysql> select * from posts; +----+-------+-------------------+---------------------+---------------------+ | id | title | body | created_at | updated_at | +----+-------+-------------------+---------------------+---------------------+ | 1 | Hello | Hello,Hello,Hello | 2021-01-04 06:32:39 | 2021-01-04 06:32:39 | +----+-------+-------------------+---------------------+---------------------+ 1 row in set (0.00 sec)
I was able to confirm that the data I posted earlier was saved in the DB.
--Generally, new action is used for new post form page, and create action is used for data saving process. --In routing, specify the GET method when browsing the Web and the POST method when sending data to the server. --In Rails, "helper method" that summarizes common processing called from view is prepared, and form_for helper is used in post form, --A mechanism called "strong parameters" is used to prevent security vulnerabilities during data transmission.