Ruby on Rails --From environment construction to simple application development on WSL2

Introduction

It's been a while since I touched Ruby on Rails. I will touch on the latest version, so I would like to help everyone by leaving this memo.

environment

Ubuntu20.04 (on Windows10 WSL2)

Ruby installation

--Execute the following command in any directory

$ sudo apt-get install ruby

--Make sure it is installed.

$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]

--It was installed, but an interesting message was output.

Suggested packages:
  apache2 | lighttpd | httpd ri ruby-dev bundler

--Here, I will also install ruby-dev, bundler, and C compiler packages.

$ sudo gem update --system
$ sudo gem install bundler
$ sudo apt-get install build-essential liblzma-dev patch ruby-dev zlib1g-dev libsqlite3-dev nodejs sqlite3

--Install rails.

$ sudo gem install rails

--Check if rails is installed. It seems that 6.0.3.1 has been installed.

$ rails -v
Rails 6.0.3.1

Project creation

Create a Hello World project

--Execute the following command. --rails new The template source code is created by executing the newly created project name.

$ rails new helloworld

new option

--I didn't specify any options this time, but you can specify the following options.

new -d option

-d dbms specification

SQL Lite3, MySQL, Oracle, PostgreSQL, FrontBase, DB / 2 can be specified as the DBMS specification. The default value is SQLLite3.

DBMS Option value
SQLLite3 sqlite3
MySQL mysql
Oracle oracle
PostgreSQL postgresql
FrontBase frontbase
DB/2 ibm_db

--If you specify mysql, it will be as follows.

$ rails new hoge_app -d mysql

new -f option

--Overwrite the file if it exists. Specify when recreating the created project.

$ rails new hoge_app -f

new -r option

--ruby Used to specify the binary path. Is it an option to use when multiple versions of ruby are installed ...

$ rails new hoge_app -r  /usr/bin/ruby2.7

new -G option

--This option does not include .gitignore.

$ rails new hoge_app -G

new-B option

--This option does not bundle install.

$ rails new hoge_app -B

new -J option

--This option does not include javascript.

$ rails new hoge_app -J

new -T option

--This option does not include test :: unit.

$ rails new hoge_app -T

Start web server

Go to the helloworld project folder you created and run the server start command.

$ cd helloworld/
$ rails s
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.
=> Booting Puma
=> Rails 6.0.3.1 application starting in development
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.5 (ruby 2.7.0-p0), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://127.0.0.1:3000
* Listening on tcp://[::1]:3000
Use Ctrl-C to stop

――Here, I would like to say, "Please connect to localhost with a browser and check." However, since my environment was built on WSL2, I devised a way to access localhost of WSL2 from the host. Is required. --Prepare a file called ```% userprofile% \ .wslconfig . The following is described in the file.

localhostForwarding=True

--After that, restart Windows. --Needless to say, if you restart, run `rails s` again to start the web server.

--Please access `http: // localhost: 3000`.

image.png

I will make a correction

――It's sad that there is no wording of Hello World even though it is called a Hello World project, so I will modify it.

--Press Ctrl + C to stop the web server.

--Make sure you are in the helloworld project. If it's a different directory, go to the helloworld directory.

$ pwd
/home/user1/dev/ror/helloworld

--Execute the following command.

$ rails g controller hello index

--As a result, hello_controller.rb was created as the controller class and index.html.erb was created under the hello directory as the view class.

image.png

--Correct the wording of the view class as follows.

rb:index.html.erb


<h1>Hello#index</h1>
<p>Find me in app/views/hello/index.html.erb</p>
<p>Hello World</p>

--Again, run `rails s` to start the web server. --Open the URL of `http: // localhost: 3000 / hello / index` in your browser.

image.png

--As expected, the wording "Hello World" could be output to the index file under the hello controller.

Implement scaffold

――Hello World is not good enough, so I will mention scaffold as well. --The scaffold generator is a function that creates CRUD operations for the defined model and reflects them in the DB. --The following is how to write

rails g scaffold model name column name:Mold...

--Example model name: todo

Column name Mold
user_id string
content string
$ rails g scaffold Todo user_id:string content:string

--As a result of the above, the source code of the mvc model is automatically generated.

image.png

--Next, create a table. ――Please recite the magic below.

$ rake db:migrate
== 20200614122106 CreateTodos: migrating ======================================
-- create_table(:todos)
   -> 0.0079s
== 20200614122106 CreateTodos: migrated (0.0102s) =============================

--Let's check with sqlite3.

rails dbconsole
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> .tables

--Execute the following as a sqlite command

sqlite> .tables
ar_internal_metadata  schema_migrations     todos

--It was confirmed that the todos table was created.

――For the time being, let's search the todos table.

sqlite> select * from todos;
sqlite>

--Exit the sqlite terminal. Press Ctrl + D.

--Now, let's start the web server. Run the familiar `rails s`. Then access the URL http: // localhost: 3000 / todos with your browser.

image.png

--The todo function is implemented without writing a single line of code. --I will try to register.

image.png

--As a result, it is displayed.

image.png

--Look at the DB table record as well.

select * from todos;
1|sample1|Development meeting from 10 o'clock|2020-06-14 12:39:29.896376|2020-06-14 12:39:29.896376
sqlite> 

--The record has been created correctly. --CRUD source code and DB table can be linked with just the scaffold generator command, so speedy development is possible.

migration generator

--What to do if the DB table changes. You may be wondering if you want to rebuild using the scaffold generator again. --In that case, use the migration generator function. Create the DB schema changes as a migration file. --rails g migration By executing the command with migration name, you can import only the DB difference. --By defining the migration name with the naming convention `Add column name To table name`, `Remove column name From table name`, you can control the addition and deletion of columns. I will. ――However, please be assured that you can change the DB table definition even if you create a migration file with a free migration name.

--As an example, let's create a migration file that adds columns to the todos table created earlier.

$ rails g migration AddColumnTodos
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.
Running via Spring preloader in process 764
      invoke  active_record
      create    db/migrate/20200614130727_add_column_todos.rb

20200614130727_add_column_todos.rb


class AddColumnTodos < ActiveRecord::Migration[6.0]
  def change
  end
end

--In the description of the migration file, you can describe the changes in `def change`, but the process will not run when lowering the migration version, so def up `` I think it is recommended to describe the changes and the contents to undo the changes in , `def down```.

――The sample is described below. --In def up, you declare that you want to add a column by doing add_column. --As the information of the column to be added, the type is defined as string in the location column. --In def down, you declare that you want to remove the column by doing remove_column. --The type is defined as string in the location column as the information of the column to be deleted.

20200614130727_add_column_todos.rb


class AddColumnTodos < ActiveRecord::Migration[6.0]
  def up
    add_column :todos, :location, :string
  end

  def down
    remove_column :todos, :location, :string
  end
end

--Let's see the current status before applying the created migration file

rails db:migrate:status
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.

database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20200614122106  Create todos
  down    20200614130727  Add column todos

--The Migration Name is Create to dos for migrations that have already been applied. --The Add column to dos migration with a status of down now represents a status that has just been created and has not yet been applied.

――So, you will execute the migration. Execute the command that was previously described as magic.

$ rake db:migrate
== 20200614130727 AddColumnTodos: migrating ===================================
-- add_column(:todos, :location, :string)
   -> 0.0049s
== 20200614130727 AddColumnTodos: migrated (0.0052s) ==========================

--Let's see the status

$ rails db:migrate:status
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.

database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20200614122106  Create todos
   up     20200614130727  Add column todos

--All Status is up. It seems that it was taken in. Let's take a look at the DB table definition.

sqlite> .schema todos
CREATE TABLE IF NOT EXISTS "todos" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "user_id" varchar, "content" varchar, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL, "location" varchar);

--It seems that the location column has been added correctly.

--Migration can also be rolled back. However, it seems to be one by one --Roll back the migration you just applied. Execute the following command.

$ rails db:rollback
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.
== 20200614130727 AddColumnTodos: reverting ===================================
-- remove_column(:todos, :location, :string)
   -> 0.0547s
== 20200614130727 AddColumnTodos: reverted (0.0553s) ==========================

--Let's see the status if the rollback was successful.

$ rails db:migrate:status
Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.

database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20200614122106  Create todos
  down    20200614130727  Add column todos

--The status of `Add column todos` is down, so it is rolled back.

--Let's take a look at the DB table as well.

.schema todos
CREATE TABLE IF NOT EXISTS "todos" ("id" integer NOT NULL PRIMARY KEY, "user_id" varchar DEFAULT NULL, "content" varchar DEFAULT NULL, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL);

--The location column is missing. It seems that you can roll back correctly.

――By making good use of migration, it is convenient to smoothly link the code and DB.

Finally

――By using Ruby on Rails, you can develop speedily. --You can create a web application that follows the CRUD of the defined model with little code. All you have to do is apply Bootstrap to the front side and retrofit it to meet your requirements. As for the back end, the skeleton of DB access logic has already been created, so you can concentrate on incorporating logic that meets the business specifications. ――I think that Java is still widely adopted in large-scale development of Web applications. It is also said that "Ruby on Rails is over. The boom is over", but I think how to use it well. I still think that speedy development can be done by using Ruby on Rails. ――Whether it's Java, Ruby on Rails, Python + Django, or C #, I think you should adopt the language and framework on a case-by-case basis, depending on the business, requirements, and the language that the engineer is good at. ――I personally would like to deepen my understanding by actually touching each language in order to correctly understand the characteristics of each language.

appendix

Recommended IDE when using WSL environment

--Visual Studio Code is a recommended IDE for building a ROR environment on WSL. The procedure is briefly described below.

To open a project on WSL from Visual Studio Code

  1. Install Remote --WSL as an extension of Visual Studio Code. image.png

  2. Click the Remote connection icon at the bottom left. image.png

  3. Select any [Remote-WSL ...] option from the palette. Here, select [Remote-WSL: New Window] image.png

  4. You can see that the icon for Remote connection at the bottom left has changed. The notation has changed to [WSL: Ubuntu-20.04]. Select Open folder ... to open the RoR project folder. image.png

  5. As shown below, you can operate the terminal by opening the explorer function in the tree on the left, the file editing function in the window on the upper right, and the terminal with "Ctrl + @", and you can perform most operations on the Visual Source Code. So it's convenient. image.png

trouble shooting

If the following error occurs when installing rails

E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/l/linux/linux-libc-dev_5.4.0-33.37_amd64.deb  404  Not Found [IP: 91.189.88.152 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

--As per the error message, please execute `sudo apt-get update`.

When a C compiler error occurs when installing rails

ERROR:  Error installing rails:
        ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.7.0/gems/nokogiri-1.10.9/ext/nokogiri
/usr/bin/ruby2.7 -I /usr/lib/ruby/2.7.0 -r ./siteconf20200614-4621-1erqs4m.rb extconf.rb
checking if the C compiler accepts ... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

--Reposted, please try installing the packages required for rails installation with the following command.

$ sudo gem update --system
$ sudo gem install bundler
$ sudo apt-get install build-essential liblzma-dev patch ruby-dev zlib1g-dev libsqlite3-dev nodejs

The site that I used as a reference

Rails documentation Rails textbook

Recommended Posts

Ruby on Rails --From environment construction to simple application development on WSL2
From 0 to Ruby on Rails environment construction [macOS] (From Homebrew installation to Rails installation)
Ruby on Rails development environment construction on M1 Mac
Environment construction of Ruby on Rails from 0 [Cloud9] (From Ruby version change to Rails installation)
[Environment construction] Ruby on Rails 5.2 system development environment construction [within 1 hour]
Deploy to Ruby on Rails Elastic beanstalk (Environment construction)
[Ruby on Rails] From MySQL construction to database change
Ruby on Rails 6.0 environment construction memo
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
[Environment construction] Get the Ruby on Rails 6 development environment within 1 hour
[Docker] Development environment construction Rails6 / Ruby2.7 / MySQL8
Muscle Ruby on Rails Day 1 ~ Environment Construction ~
Ruby on Rails development environment construction with Docker + VSCode (Remote Container)
Steps to build a Ruby on Rails development environment with Vagrant
How to link Rails6 Vue (from environment construction)
[Personal memo] Ruby on Rails environment construction (Windows)
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
[Error] Switch environment construction to use Ruby on Rails oss (open source)
How to solve the local environment construction of Ruby on Rails (MAC)!
How to build a Ruby on Rails development environment with Docker (Rails 5.x)
Rails6 development environment construction [Mac]
[Introduction] Try to create a Ruby on Rails application
Rails engineer environment construction ruby2.7.1
Build a Ruby on Rails development environment on AWS Cloud9
Rails environment construction Rails5.2.1 ruby2.5.1 Catalina
Docker the development environment of Ruby on Rails project
[Updated from time to time] Ruby on Rails Convenient methods
[Environment construction Mac] Ruby on Rails (+ Webpacker handles errors)
Ruby on Rails environment construction using VirtualBox, Vagrant, cyberduck
JavaFX application development with IntelliJ IDEA and Gradle ~ From environment construction to sample code ~
From Ruby on Rails error message display to Japanese localization
Rails application development environment construction with Docker [Docker, Rails, Puma, Nginx, MySQL]
Environment construction for Servlet application development
How to use Ruby on Rails
Rails on Docker environment construction procedure
[Environment construction] Uninstall rails from local
From building to deploying Ruby on Jets in docker-compose environment <Part 2>
From building to deploying Ruby on Jets in docker-compose environment <Part 1>
Build a development environment where Ruby on Rails breakpoints work on Windows
Notes on building Kotlin development environment and migrating from Java to Kotlin
PostgreSQL environment construction with Docker (from setup to just before development)
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 use CarrierWave
How to make an application with ruby on rails (assuming that the environment has been built)
Java development environment construction memo on Mac
Deploy to Heroku [Ruby on Rails] Beginner
[Ruby] Building a Ruby development environment on Ubuntu
Preparing to introduce jQuery to Ruby on Rails
Ruby on Rails application new creation command
[Ruby on Rails] How to use redirect_to
[Ruby on Rails] How to use kaminari
[Ruby on Rails] Button to return to top
CentOS8.2 (x86_64) + ruby2.5 + Rails5.2 + MariaDB (10.3.17) environment construction
Change from SQLite3 to PostgreSQL in a new Ruby on Rails project
How to build a Ruby on Rails environment using Docker (for Docker beginners)
Ruby on Rails ✕ Docker ✕ MySQL Introducing Docker and docker-compose to apps under development
Try running ScalarDB on WSL Ubuntu (Environment Construction)
[Jakarta EE 8 application development with Gradle] 1. Environment construction
[Ruby on Rails] How to display error messages
How to add / remove Ruby on Rails columns
Try deploying Rails application to EC2-Part 2 (Server construction)-