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 ~
A database is a place to store data.
In Ruby on Rails, you can operate the database by creating a model from the 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.
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.
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 %>
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.
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.
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.
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.
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.
Let's check the created database.
You can start the database client with the following code.
rails dbconsole
After starting the database client, you can display the table list with the following code.
sqlite>.table
ar_internal_metadata schema_migrations users
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);
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.
The database is accessed using a model.
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>
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