[Ruby] Rails CRUD function implementation ① (this time, new addition, deletion)

4 minute read

Purpose of this article

This is the procedure for creating a web application with a CRUD function that uses rails. This is a site (birdtweet) where you can post photos and names of birds.

Create rails application

Specify rails version 6.0.0. Specify the DB (mysql this time) to be used after -d.

rails _6.0.0_ new birdtweet -d mysql

setting change.

config/database.yml


...
# encoding: utf8mb4
  encoding: utf8
...

DB creation

cd birdtweet
rails db:create

Edit Gemfile Open Gemfile directly under the project

Gemfile


# gem'mysql2','>= 0.4.4'
gem'mysql2','>= 0.5.3'
........
(Bottom line of file)
gem'pry-rails'

Update settings in terminal

bundle update

Create model

At the terminal

rails g model bird

Add column

...
create_table :birds do |t|
      t.string :name
      t.text :pic
      t.timestamps
end
...

Update changes with command!

rails db:migrate

Populate the DB with some data in the console.

rails c
Bird.create(name: "puffin", pic: "https://cdn.pixabay.com/photo/2020/05/26/13/22/puffins-5223057_1280.jpg")
Bird.create(name: "kingfisher", pic: "https://cdn.pixabay.com/photo/2017/02/07/16/47/kingfisher-2046453_1280.jpg")
exit

Create controller

Create the controller with the following command.

rails g controller birds

It’s confusing to make it plural or not, Only the model is singular!

Flow from here

The flow of creating each function is almost the same!

Added to routes.rb ↓ Added links to each function in index.html.erb (unexpected index) ↓ Added to birds_controller.rb ↓ Function name.html.erb creation

List display function

rails has 7 actions.

  • index: List
  • show: Details
  • new: Transition to new creation screen
  • create: Save new data
  • edit: Transition to edit screen
  • update: Update edit contents
  • destroy: Delete

If you don’t want to use all the functions, specify only the ones you use with the only option.

config/routes.rb


After # resources, the plural model name
  resources :birds, only: :index

app/controllers/birds_controller.rb


...
def index
    Store the Bird model data in the # instance variable.
    @birds = Bird.all
  end
...

Create index.html.erb file Show all instance variables in the view using the each method.

rb:app/views/birds/index.html.erb


<% @birds.each do |bird| %>
<%= bird.name %>
<div style=
"background-image: url(<%= bird.pic %>);
 background-position: center center;
 background-size: cover;
 width: 300px;
 height: 300px;
 margin-bottom: 10px;
 ">
</div>
<%end%>

It was displayed as follows! !! !! image.png

New posting function

The flow is also routes → controller → view, but since it is data addition (create) from moving to the posting screen (new), the series of flows is done twice!

routes.rb


Rails.application.routes.draw do
  After # resources, the plural model name
  #If there are multiple actions, we will make them into an array.
  resources :birds, only: [:index, :new]
end

ruby:index.html.erb


<%=link_to'new post', new_bird_path, method: :get%>
...

image.png

birds_controller.rb


...
def new
  Store the instance of #Bird model in the instance variable.
  @bird = Bird.new
end
...

create new.html.erb

rb:app/views/birds/new.html.erb


<%# Judgment will be made from the model put in the instance variable without mentioning the transition destination url %>
<%=form_with(model: @bird, local: true) do |form| %>
  <%= form.text_field :name, placeholder: "bird name" %>
  <%= form.text_field :pic, placeholder: "bird photo URL" %>
  <%= form.submit "post" %>
<%end%>

http://localhost:3000/birds/new You can create a posting screen by accessing! image.png

Next is the function to register the input information.

routes.rb


Rails.application.routes.draw do
  After # resources, the plural model name
  #If there are multiple actions, we will make them into an array.
  resources :birds, only: [:index, :new, :create]
end

birds_controller.rb Data is sent in the form of hash from form.
It is dangerous to receive all the data!
Although you only have to use the name and URL of the photo, you can maliciously add the login information key and change the login information of another person and hijack it. So we will use strong parameters.
Further, below the line where private is written, the method cannot be called from other files. This has the advantage of reducing the number of files to look at when there are more methods.

birds_controller.rb


...
  def create
    Receive the parameter specified by bird_param defined under #private and save it.
    Bird.create(bird_param)
  end

  private
  def bird_param
# params.require(:model name).permit(:column name,:column name,......)
    params.require(:bird).permit(:name, :pic)
  end
...

create.html.erb

rb:app/views/birds/create.html.erb


<h3> Post completed! </h3>
<a href="/birds">To list</a>

image.png

image.png

If you leave it as it is, you can register without entering anything. Therefore, the description for validation check is given.

app/models/birds.rb


class Bird <ApplicationRecord
  # Write the column name you want to make mandatory.
  validates :name, presence: true
  validates :pic, presence: true
end

Now you can no longer register the data! !!

Delete function

routes.rb


...
resources :birds, only: [:index, :new, :create, :destroy]
...

To check the link to the delete function, first use the command

rails routes

will do. Then the following output is output. If you add “_path” to the Prefix value, the URL described in the URI will be output. image.pngThis time it’s deleted, so pay attention to the line that says DELETE on the Verb. The Prefix is “bird”, so it should be “bird_path”. The method has “DELETE” in “Verb”, so it should be “delete”. After that, I will also pass the id!

index.html.erb


...
<%= bird.name %><%=link_to "delete", bird_path(bird.id), method: :delete%>
...

The link is displayed. image.png

bird_controller.rb


...
  def destroy
# This time, we will not send the extracted data anywhere, so we will not add @.
    bird = Bird.find(params[:id])
    bird.destroy
  end
...

destroy.html.erb


<a href="/birds">List screen</a>

image.png image.png Puffin has been removed properly!

Tags: ,

Updated: