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

Purpose of this article It is a procedure to create a web application with CRUD function using rails. It is a site (bird tweet) where you can post pictures and names of birds.

Creating a rails application

Specify version 6.0.0 of rails. Specify the DB (mysql in this case) 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

Editing Gemfile Open the 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 the terminal

bundle update

Creating a model At the terminal
rails g model bird

Add column

db/migrate/2020********create_birds.rb


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

Update your changes with commands!

rails db:migrate

Put some data in the DB at 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

Creating a controller Create a controller with the following command.
rails g controller birds

Pluralized or not, confusing, 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 edits
  • destroy: Delete

If you do not want to use all the functions, specify only the ones to be used with the only option.

config/routes.rb


#Behind resources is the plural of the model name
  resources :birds, only: :index

app/controllers/birds_controller.rb


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

index.html.erb file creation Display 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 below! !! !! image.png

New posting function The flow is also routes → controller → view, but since data is added (create) from moving to the posting screen (new), we will do a series of flows twice!

routes.rb


Rails.application.routes.draw do
  #Behind resources is the plural of the model name
  #If there are multiple actions, I will make it in the form of 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 instantiated version of the Bird model in an instance variable.
  @bird = Bird.new
end
...

Create new.html.erb

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


<%#Even if you do not describe the transition destination url, it will transition based on the model put in the instance variable.%>
<%=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 see the posting screen when you access! image.png

Next is the function to register the input information.

routes.rb


Rails.application.routes.draw do
  #Behind resources is the plural of the model name
  #If there are multiple actions, I will make it in the form of an array
  resources :birds, only: [:index, :new, :create]
end

birds_controller.rb The data will be sent in the form of a hash from the form.
It is dangerous to receive all the data! </ b>
Even though only the name and URL of the photo are required, the login information key can be maliciously added, and the login information of another person can be changed and hijacked without permission. So we use strong parameters.
Also, below the line that describes private, it is a method that cannot be called from other files. The advantage is that you can see fewer files when you have more methods.

birds_controller.rb


...
  def create
    #bird defined under private_Receives the parameter specified by param and saves 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 create

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


<h3>Posting completed!</h3>
<a href="/birds">To List</a>

image.png

image.png

If you leave it as it is, you will be able to register without entering anything. Therefore, I will write a description for validation check.

app/models/birds.rb


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

You can no longer register the data from now on! !!

Delete function

routes.rb


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

To find the link to the delete function, first use the command.

rails routes

will do. Then, the following output will be output. If you add "_path" to the Prefix value, the URL described in the URI will be output. image.png

This time it's deleted, so pay attention to the line that says DELETE in the verb. Prefix is "bird", so you can set it to "bird_path". The method is "DELETE" in "Verb", so you can just say "delete". After that, pass the id as well!

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 I will not send the extracted data anywhere, so@Do not attach.
    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!

Recommended Posts

Rails CRUD function implementation ① (new addition, deletion this time)
Rails CRUD function implementation ② (edited and detailed this time)
Rails Basic CRUD function implementation procedure scaffold
Rails search function implementation
Rails fuzzy search function implementation
[Rails 6] Implementation of search function
Login function implementation with rails
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Rails 6] Pagination function implementation (kaminari)
[Rails] Implementation of new registration function in wizard format using devise
[Rails] Implementation of user logic deletion
[Rails] Implementation of CSV import function
[Rails] Asynchronous implementation of like function
[Rails] Implementation of image preview function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
[Rails] Comment function (registration / display / deletion)
[Rails 6] Implementation of new registration function by SNS authentication (Facebook, Google)
[Rails] Implementation of coupon function (with automatic deletion function using batch processing)
[Rails] gem ancestry category function implementation
[Ruby on Rails] Comment function implementation
[Rails 6] Like function (synchronous → asynchronous) implementation
[Rails] Comment function implementation procedure memo
[Rails] Addition of Ruby On Rails comment function
Rails Addition of easy and easy login function
Rails [For beginners] Implementation of comment function
[Rails 6] Implementation of SNS (Twitter) sharing function
[Vue.js] Implementation of menu function Implementation version rails6
[Ruby on rails] Implementation of like function
[Vue.js] Implementation of menu function Vue.js introduction rails6
[Ruby on Rails] Logical deletion (withdrawal function)
[Rails] Implementation of search function using gem's ransack
Implementation of Ruby on Rails login function (Session)
[Rails] Implementation of image enlargement function using lightbox2
[Rails] Implementation of retweet function in SNS application
Ruby on Rails Email automatic sending function implementation