Explanation of Ruby on rails for beginners ③ ~ Creating a database ~

Introduction

This time it 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 ~

What is a database?

A database is a place to store data.

In Ruby on Rails, you can operate the database by creating a model from the controller. image.png

Creating a controller

This time, consider creating a database that stores user IDs and passwords.

Before creating the database, let's create the controller and action once.

Execute the following code in the terminal.

rails g controller users index

You have now created a user controller and added an index action to it. In the rails g command, you can set two names, the controller name and the action name.

Please route as follows.

routes.rb


get 'users/index' => "users#index"

Now you can perform the index action on the user controller when the user sends you the URL ʻuser / index`.

Let's check the user controller. This time, the action has been added from the beginning.

users_controller.rb


class UsersController < ApplicationController
  def index
  end
end

In fact, the view file is also automatically generated.

image.png

Let's write the index.html.erb file as follows.

index.html.erb


<h1>Users#index</h1>
<p>Find me in app/views/users/index.html.erb</p>

Access this file at the following URL.

http://localhost:3000/users/index

The following screen will appear.

image.png

Pass variables from action to view file

image.png

The controller looks for the view file and returns it to the user.

At that time, by defining a variable for the action in the controller, that variable can be used in the view file.

Let's define the variables as follows.

users_controller.rb


class UsersController < ApplicationController
  def index
    @users = ["maru", "poco"]
  end
end

By using @ before a variable like @user, that variable becomes an instance variable. There was an explanation in here.

In this way, when passing variables from the controller to the view file, use instance variables instead of local variables.

Use instance variables in Rails controllers in the following cases: -Passing data between methods (typically loading data with before_action) · Passing data to the view

In this way, instance variables created with @ variables can be used in the view file.

index.html.erb


<% @users.each do |user| %>
  <div>
    <%= user %>
  </div>
<% end %>

image.png

Since @users has an array stored, it can be retrieved with .each do ~ end. This part is all Ruby code, so let's put it in <%%>. The point is that it is sandwiched between <%%> instead of <% =%> because it does not need to be displayed in the browser.

Display it in the browser at the part of <% = user%>.

This time, I used it by defining an array in the action of the controller and passing it to the view file.

Now consider bringing data from the database into an action and passing it to a view file.

Creating a model

image.png

In order to work with the database, you need to create a model.

A model is a mechanism for manipulating database information. Alternatively, it can be called a class that interacts with the database.

With the model in the code below. Create a migration file.

rails g model user name:string password:string

User is the model name, id and password are the columns. Columns are the vertical data in the database, or columns.

The database created by this code looks like the table below.

image.png

The entire table is called the table, the vertical data is called the column, and the horizontal data is called the record. A model is a Ruby class that corresponds to this database, and an instance of the model class is an object that represents one row (record) and has attributes that correspond to the columns (columns) of the table.

Running the above code will create a migration file and a model to create the database.

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.string :name
      t.string :password

      t.timestamps
    end
  end
end

user.rb


class User < ApplicationRecord
end

You can create a database by importing the migration file created above with the code below.

rails db:migrate

At this point, you have created a database.

Now let's summarize what a migration file is.

What is a migration file?

A migration file is like a blueprint for creating a database.

By executing the migration file, you can create a data table based on its contents.

In rails, running the rails g model command will generate both a migration file and a model.

Keep in mind that migration files are a tool for creating a database framework, and models are like a tool that bridges the database and controllers.

Save data to database

Let's start the Rails console with the following code.

rails console

After launching the console, let's use the model to store the data in the database.

user = User.new(name: "poco", password: "maru")
user.save

You have now saved the data in the database.

Check the database

Let's check the created database.

Start database client

You can start the database client with the following code.

rails dbconsole

List table

After starting the database client, you can display the table list with the following code.

sqlite>.table

ar_internal_metadata schema_migrations users

Schema display

You can view the schema with the following code. Schema means structure. You can check the structure of the specified database.

sqlite>.schema users

CREATE TABLE IF NOT EXISTS "users" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "password" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);

Stop database client

You can stop the database client with the following code.

sqlite>.quit

At this point, you have created a database.

Let's actually use the database.

Use of database

The database is accessed using a model.

image.png

When using the database, access it from the controller using the model.

users_controller.rb


class UsersController < ApplicationController
  def index
    @user = User.first
  end
end

You can now use the instance variable @user in your index.html.erb file.

@user contains the record for the very first column of the users table.

Use it in the index.html.erb file as follows:

index.html.erb


<p><%= @user.name %></p>
<p><%= @user.password %></p>

image.png

At the end

That's all for this time.

Thank you for staying with us so far.

Please see the following articles if you like.

Explanation of Ruby on rails for beginners ④ ~ How to use naming convention and form_Tag ~

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

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 ③ ~ Creating a database ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
Explanation of Ruby on rails for beginners ①
Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Ruby on Rails for beginners! !! Summary of new posting functions
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
[Ruby on Rails] About bundler (for beginners)
Explanation of Ruby on rails for beginners ④ ~ Naming convention and how to use form_Tag ~
(Ruby on Rails6) Creating a database and displaying it in a view
[Ruby on Rails] A memorandum of layout templates
(Ruby on Rails6) Creating data in a table
[For beginners] Procedure for creating a controller using rails
How to build a Ruby on Rails environment using Docker (for Docker beginners)
A note about the seed function of Ruby on Rails
Ruby on Rails for beginners! !! Post list / detailed display function summary
Create a development environment for Ruby 3.0.0 and Rails 6.1.0 on Ubuntu 20.04.1 LTS
[Ruby on Rails] How to avoid creating unnecessary routes for devise
[Ruby on Rails] Introduction of initial data
[Rails] Addition of Ruby On Rails comment function
[Ruby on Rails] Creating an inquiry form
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] Japanese notation of errors
Rails Basics of creating a new application
[Ruby on rails] Implementation of like function
Beginners create portfolio in Ruby on Rails
[Ruby on Rails] Create a pie chart for each column with Chartkick
[Ruby] Explanation for beginners of iterative processing with subscripts such as each_with_index!
Ruby on Rails DB Tips for creating methods to reduce the load
A series of flow of table creation → record creation, deletion → table deletion in Ruby on Rails
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
Building a Ruby environment for classes on Mac
[Ruby on Rails] Select2 introduction memo for Webpacker
Ruby on Rails ~ Basics of MVC and Router ~
Introducing Rspec, a Ruby on Rails test framework
A collection of simple questions for Java beginners
[For beginners] Procedure for creating a controller using rails
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
[Rails] Complete routing settings
[Ruby on Rails] Individual display of error messages
I made a portfolio with Ruby On Rails
[Ruby on Rails] Implement a pie chart that specifies the percentage of colors
Ruby on Rails basics
Ruby On Rails Association
Scraping for beginners (Ruby)
A review of the code used by rails beginners
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
Build a Ruby on Rails development environment on AWS Cloud9
Implementation of Ruby on Rails login function (devise edition)
Docker the development environment of Ruby on Rails project
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Ruby on Rails] From MySQL construction to database change
Try using the query attribute of Ruby on Rails
[For beginners] Explanation of classes, instances, and statics in Java
Ruby on rails learning record -2020.10.03
Tutorial to create a blog with Rails for beginners Part 1