Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~

Introduction

This time is a continuation of the previous article.

Please see the previous article if you like.

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 ~

View database data list

Let's get the data of the users table and display it with the following code.

index.html.erb


 <% @users.each do |user| %>
   <p>name</p>
   <div class="ruby-name"><%= user.name %></div>
 <% end %>

I'm passing it in the controller to use the instance variable @users.

users_controller.rb


def index
  @users = User.all
end

The following screen will be displayed.

image.png

In addition, css is specified as follows.

users.scss


.ruby-name {
    color: purple;
    display: inline-block;
    font-weight: bold;
}

Delete database

Now let's implement database deletion.

Rewrite the code as follows.

index.html.erb


 <% @users.each do |user| %>
   <p>name</p>
   <div class="ruby-name">
     <%= user.name %>
     <%= link_to("Delete", "/users/#{user.id}/destroy", {method: "post"})%>
   </div>
 <% end %>

image.png

I was able to delete the element by clicking the delete button.

image.png

Let's look at the specific processing. The following code has been added to index.html.erb.

<%= link_to("Delete", "/users/#{user.id}/destroy", {method: "post"})%>

This will cause the second argument to be processed when you click Delete.

The second argument "/users/#{user.id}/destroy" includes the database id in the routing to the destroy action of the users controller. By specifying the URL in this way, the controller can receive the id of the database you want to delete.

The third argument specifies that this is a post request, not a get request.

Please route as follows.

routes.rb


post "users/:id/destroy" => "users#destroy"

The: id part can accept any number. The received number is stored in params [: id] in the users controller.

Code your controller as follows:

users_controller.rb


def destroy
  user = User.find_by(id: params[:id])
  user.destroy
  redirect_to("/users/index")
end

In the part of ʻuser = User.find_by (id: params [: id])`, the data is extracted from the database using the model. Extract the data with the same id as the id sent from index.html.erb from the database and store it in user.

ʻThe data is deleted in the part of user.destroy`.

At the redirect_to ("/ users / index ") part, we are redirecting to index.html.erb. This time, it will be reloaded because it is the operation when the delete link is clicked from index.html.erb.

At this point, you have successfully deleted the data from the database.

Database editing

Next, let's edit the database.

Edit ʻindex.html.erb` as follows:

index.html.erb


 <% @users.each do |user| %>
   <p>name</p>
   <div class="ruby-name">
     <%= user.name %>
     <%= link_to("Delete", "/users/#{user.id}/destroy", {method: "post"})%>
     <%= link_to("Edit", "/users/#{user.id}/edit") %>
   </div>
 <% end %>

Newly added this time is the <% = link_to ("edit "," / users / # {user.id} / edit ")%> part.

This will take you to a new view file called ʻusers / edit`.

At that time, you will pass the id of the database you want to edit to the view file.

Route as follows:

routes.rb


get "users/:id/edit" => "users#edit"

Prepare the following view file in the following path. image.png

edit.html.erb


<%= form_tag("/users/#{@user.id}/update") do  %>
  <input type="text" value="<%[email protected]%>" name="new_name">
  <input type="submit" value="Send">
<% end %>

As a test, click the part that says Edit index.html.erb file below. image.png

It will be as follows. image.png

Here is a description of the edit.html.erb file.

The form_tag ("/ users / # {@ user.id} / update ") part specifies which action of which controller to use.

This time we will use the update action of the users controller. Also, to edit the database, send the id of the database you want to edit. form_tag was a post request.

In the part of <input type =" text "value =" <% [email protected]%> "name =" new_name ">, the initial value and name of the input tag are set. @user is sent from the edit action of the users controller.

users_controller.rb


def edit
  @user = User.find_by(id: params[:id])
end

@ User contains the value found in the database according to id.

Now, let's change the value as shown below and send it.

image.png

Then, the following routing will execute the update action of the users controller.

routes.rb


post "users/:id/update" => "users#update"

users_controller.rb


def update
  user = User.find_by(id: params[:id])
  user.name = params[:new_name]
  user.save
  redirect_to("/users/index")
end

In the update action, search the database according to the sent id, store it in the local variable user, rewrite the data in the name column to the new name sent, and save it with ʻuser.save. After that, I'm redirecting to / users / index`.

Therefore, it changes as follows.

image.png

At the end

This is the end of this article.

Thank you for your relationship.

Please see the following articles if you like.

Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~

Explanation of Ruby on rails for beginners ⑦ ~ Implementation of flash ~

Recommended Posts

Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
Explanation of Ruby on rails for beginners ①
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
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 ~
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
[Ruby on Rails] About bundler (for beginners)
Ruby on Rails ~ Basics of MVC and Router ~
[For beginners] Explanation of classes, instances, and statics in Java
(Ruby on Rails6) Display of the database that got the id of the database
Delete all the contents of the list page [Ruby on Rails]
Basic knowledge of Ruby on Rails
Ruby on Rails for beginners! !! Post list / detailed display function summary
(Ruby on Rails6) Creating a database and displaying it in a view
Create a development environment for Ruby 3.0.0 and Rails 6.1.0 on Ubuntu 20.04.1 LTS
[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
Explanation of Ruby Time and Date objects
Rails [For beginners] Implementation of comment function
Ruby on Rails controller create / delete 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)
[Ruby] Explanation for beginners of iterative processing with subscripts such as each_with_index!
[Rails] Articles for beginners to organize and understand the flow of form_with
Validation settings for Ruby on Rails login function
Implementation of Ruby on Rails login function (Session)
[Ruby on Rails] Until the introduction of RSpec
Recommendation of Service class in Ruby on Rails
[Ruby on Rails] A memorandum of layout templates
[Rails] Procedure for linking databases with Ruby On Rails
[Ruby on Rails] Post editing function (update, delete)
[Ruby on Rails] Individual display of error messages
[Ruby on Rails] Add and delete tags and display (success / error) messages using ajax.
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
[For beginners] DI ~ The basics of DI and DI in Spring ~
Implementation of Ruby on Rails login function (devise edition)
Docker the development environment of Ruby on Rails project
[Ruby on Rails] Delete s3 images with Active Strage
[Ruby On Rails] Causes and remedies for ActionView :: Template :: Error (ActiveStorage :: InvariableError) (hypothesis / verification)
[Ruby on Rails] Implementation of tagging function/tag filtering function
Ruby on Rails Elementary
Ruby on Rails basics
List of frequently used Java instructions (for beginners and beginners)
Ruby On Rails Association
[Ruby on Rails] From MySQL construction to database change
(Ruby on Rails6) How to create models and tables
Try using the query attribute of Ruby on Rails
Scraping for beginners (Ruby)
[Ruby On Rails] How to search and save the data of the parent table from the child table
<For super beginners> Why don't you make a chatbot using "Talk API"? ?? [Ruby on Rails]
[Ruby on Rails] Only the user who posted can edit
Rails: I've summarized the model and database for a moment.
[For Ruby beginners] Explain how to freely delete array elements!
[Ruby on Rails] Elimination of Fat Controller-First, logic to model-