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.
Ubuntu20.04 (on Windows10 WSL2)
--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
--Execute the following command. --rails new The template source code is created by executing the newly created project name.
$ rails new helloworld
--I didn't specify any options this time, but you can specify the following options.
-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
--Overwrite the file if it exists. Specify when recreating the created project.
$ rails new hoge_app -f
--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
--This option does not include .gitignore.
$ rails new hoge_app -G
--This option does not bundle install.
$ rails new hoge_app -B
--This option does not include javascript.
$ rails new hoge_app -J
--This option does not include test :: unit.
$ rails new hoge_app -T
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`
.
――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.
--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.
--As expected, the wording "Hello World" could be output to the index file under the hello controller.
――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.
--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.
--The todo function is implemented without writing a single line of code. --I will try to register.
--As a result, it is displayed.
--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.
--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.
――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.
--Visual Studio Code is a recommended IDE for building a ROR environment on WSL. The procedure is briefly described below.
Install Remote --WSL as an extension of Visual Studio Code.
Click the Remote connection icon at the bottom left.
Select any [Remote-WSL ...] option from the palette. Here, select [Remote-WSL: New Window]
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.
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.
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`
.
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
Rails documentation Rails textbook
Recommended Posts