[DOCKER] Ruby on Rails for beginners! !! Summary of new posting functions


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.

Development environment

Advance preparation

I created a Post model and edited my graying file in advance. I edited the migration file as follows.

Migration file

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

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.

List of actions defined in the controller

In Rails, it is common to define the basic functions of a web application with the following action names.

Action name role
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
delete Delete data

New creation function (new, create)

Creating a controller

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
  #Add up to here

Routing settings

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

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 view

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.


<h1>Post form</h1>

Now when you access the/posts/new path from your browser, you'll see the view file you just created.

スクリーンショット 2021-01-04 20.31.03.png

Creating a post form

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

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| %>
  <%= f.text_field :title %>
  <%= 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. スクリーンショット 2021-01-04 20.24.16.png

Implementation of data storage function (create)

First, set the routing.


Rails.application.routes.draw do
  get 'posts/new' => 'posts#new'
  #from here
  post 'posts' => 'posts#create'
  #Add up to here

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)
    redirect_to '/posts/new'

  def post_params
    params.require(:post).permit(:title, :body)

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.


redirect_to '/posts/new'

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.

スクリーンショット 2021-01-04 20.26.43.png

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.

Recommended Posts

Ruby on Rails for beginners! !! Summary of new posting functions
Explanation of Ruby on rails for beginners ①
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
[Ruby on Rails] About bundler (for beginners)
Ruby on Rails for beginners! !! Post list / detailed display function summary
Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
Ruby on Rails validation summary
[Ruby on Rails] Asynchronous communication of posting function, ajax
Ruby on Rails Overview (Beginner Summary)
Summary of rails validation (for myself)
[For beginners] Summary of java constructor
Ruby on Rails variable, constant summary
Basic knowledge of Ruby on Rails
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
[Ruby on Rails] "|| =" ← Summary of how to use this assignment operator
[Ruby on Rails] Introduction of initial data
[Rails] Addition of Ruby On Rails comment function
Let's summarize "MVC" of Ruby on Rails
part of the syntax of ruby ​​on rails
Rails [For beginners] Implementation of comment function
Ruby on Rails application new creation command
[Ruby on Rails] Japanese notation of errors
[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)
[For Rails beginners] Summary of how to use RSpec (get an overview)
Validation settings for Ruby on Rails login function
Implementation of Ruby on Rails login function (Session)
A brief summary of Bootstrap features for beginners
[Ruby on Rails] Until the introduction of RSpec
Recommendation of Service class in Ruby on Rails
[Ruby on Rails] Select2 introduction memo for Webpacker
Rails new in Ruby on Rails ~ Memorandum until deployment 2
Ruby on Rails ~ Basics of MVC and Router ~
[Ruby on Rails] A memorandum of layout templates
Rails new in Ruby on Rails ~ Memorandum until deployment 1
[Rails] Procedure for linking databases with Ruby On Rails
[Ruby on Rails] Individual display of error messages
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
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)
Method summary to update multiple columns [Ruby on Rails]
Implementation of Ruby on Rails login function (devise edition)
Docker the development environment of Ruby on Rails project
[Ruby on Rails] Posting score ranking function (whole display)
[Ruby on Rails] Implementation of tagging function/tag filtering function
Ruby on Rails Refactoring method example summary around MVC
Try using the query attribute of Ruby on Rails
Ruby on rails learning record -2020.10.03
<For super beginners> Why don't you make a chatbot using "Talk API"? ?? [Ruby on Rails]
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05