(Ruby on Rails6) Creating a database and displaying it in a view

Machine spec / version

-Version 10.15.3 ・ Ruby ruby 2.6.3p62 ・ Rails 6.0.3.2

Preface

In this article, I will record the creation of the database in Ruby on Rails6 and the display in the view as an oblivion. If you are having trouble creating a database, I hope you find it useful.

Preparation

Here, we will start by creating a directory. The database creation will be described later, so if you know it, you can skip it!

Creating a directory

Enter the following command in any directory. Also, since it is supposed to be deployed on heroku, the database (postgresql) is set.

terminal


rails new directory name-TB --database=postgresql

(Example)↓
rails new form_test -TB --database=postgresql

If you don't have a database to set, you can use the following command.

terminal


rails new directory name

(Example)↓
rails new form_test

Creating a page

Let's move to the directory you just created and create a page.

terminal


cd directory name

(Example ↓)
cd form_test

terminal


rails generate controller arbitrary name index

(Example)↓
rails generate controller Forms index

For "index", change the input name with the intention of creating it. There is no problem with the abbreviated command of generate → g. Also, the directory name should be pluralized, such as "Forms", for easier management later.

terminal


rails g controller arbitrary name index

(Example)↓
rails g controller Forms index

routes settings

If you set the following to routes, it will be set to http: // localhost: 3000 / forms.

config/routes


Rails.application.routes.draw do
  # get "Arbitrary name" => "Arbitrary value#index"
    get "forms" => "forms#index"
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Check with browser

I will check it with a browser once. Enter the command to display in the browser.

terminal


rails s
or
rails server

Was it displayed?

Also, I wrote it in postgresql directory creation, but I may get an error (I got an error) In that case, enter the following command.

terminal


rails db:create

The cause of the error will be explained in another article.

Prepare the database

From here, we will create the database.

Create database

terminal


rails g model database name content:text
(Example)↓
rails g model Forms content:text

Database names are easier to manage with the initial "uppercase" and "plural". Not omitted ↓ But OK

terminal


rails generate model database name content:text
(Example)↓
rails generate model Forms content:text

Database migration

After creating the database, please migrate. If you forget it, you will get an error when checking in your browser.

terminal


rails db:migrate

Added database post

Instantiate. To do this, type rails console first in the command.

terminal


rails console

Arbitrary name=Database name.new(content: "I'm studying Rails at Progate from today!")
Arbitrary name.save

(Example)↓
form1 = Form.new(content: "test")
form1.save

As an aside, if you enter ↓ when creating a directory, it will be "forms (plural form)", so it is better to set it to "form (singular form)" when adding a database.

terminal


rails generate controller forms index

Save database posts

After adding a post, please save. By doing this, your post will be saved.

terminal


Arbitrary name.save

(Example)↓
form1.save

quit

quit is the command to exit the rails console. You can save multiple posts by repeating this process 2 ~.

Get database posts

terminal


This time i"Directory name=Database name.all"Is used.

Directory name=Database name.all
forms = Form.all
→ Get all values

Directory name[0]
forms[0]
→ Get the first value

Directory name[0].content
forms[0].content
→ Initial value(content)Get

That's all for creating the database. Next, we will work on displaying it in the view.

Save database contents to view

Control settings

You can get all the posted contents by setting "directory name = database name.all" used for fetching the database in controller.

Also, in Ruby, "form" must have an @ like "@form".

app/controllers/Any_controller.rb


class PostsController < ApplicationController
  def index
  # @Directory name=Database name.all
    @forms = Form.all
  end
end

View settings and Each array

rb:app/views/Any/index.html.erb


<h1>Forms#index</h1>
<p>Find me in app/views/forms/index.html.erb</p>
 <% @Directory name.each do |form| %>
      <div>
     <%=Singular form of directory name.content %>
      </div>
  <% end %>

Example ↓

rb:app/views/Any/index.html.erb


<h1>Forms#index</h1>
<p>Find me in app/views/forms/index.html.erb</p>
 <% @forms.each do |form| %>
      <div>
        <%= form.content %>
      </div>
 <% end %>

Iterative processing by Each

rb:app/views/Any/index.html.erb


 <% @forms.each do |form| %>
processing
 <% end %>

You can iterate by using each. Also

rb:app/views/Any/index.html.erb


<%= form.content %>

Is displaying the "contents" of the database.

And, please note that in Ruby, different behavior occurs due to the difference in the notation of ↓. Here, we want to display the contents of the database, so enter <% = form.content%>.

rb:app/views/Any/index.html.erb


<%= form.content %>
→ Display the character string in the view(=Important)

<% form.content %>
→ Do not display the result of the character string in the view

Check with browser

rails_db-test.png If there is no problem, you can check it at the route destination. I tried to display test1 and test2 in the test.

The above tests are published on Github. If you want to try it, please download it.

Github

Afterword

Thank you for reading this far. That's all for creating a database and displaying it in a view in Ruby on Rails6. The routes and controller settings are complicated and a little tiring, but I hope they are displayed in the view.

Reference link

Books: <a href="https://www.amazon.co.jp/%E3%81%9F%E3%81%AE%E3%81%97%E3%81%84Ruby-%E7%AC%AC6 % E7% 89% 88-Informatics-IDEA-% E9% AB% 98% E6% A9% 8B / dp / 4797399848 / ref = sr_1_1? __mk_ja_JP =% E3% 82% AB% E3% 82% BF% E3% 82 % AB% E3% 83% 8A & dchild = 1 & keywords =% E3% 81% 9F% E3% 81% AE% E3% 81% 97% E3% 81% 84Ruby +% E7% AC% AC6% E7% 89% 88 & qid = 1600088731 & s = books & sr = 1-1 "target =" blank "> Fun Ruby 6th Edition

My link

Also, there is a link to the Twitter portfolio, so if you are interested, Please connect. I would be very happy to have friends who can share programming learning.

Twitter Portfolio Github

Recommended Posts

(Ruby on Rails6) Creating a database and displaying it in a view
(Ruby on Rails6) Creating data in a table
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
Apply CSS to a specific View in Ruby on Rails
Difficulties in building a Ruby on Rails environment (Windows 10) (SQLite3)
How to display a graph in Ruby on Rails (LazyHighChart)
Ruby on Rails Japanese-English support i18n
Explanation of Ruby on rails for beginners ⑤ ~ Edit and delete database ~
Create a development environment for Ruby 3.0.0 and Rails 6.1.0 on Ubuntu 20.04.1 LTS
Things to remember and concepts in the Ruby on Rails tutorial
[Ruby on Rails] View test with RSpec
Ruby on Rails in Visual Studio Codespaces
Beginners create portfolio in Ruby on Rails
Change from SQLite3 to PostgreSQL in a new Ruby on Rails project
How to create a query using variables in GraphQL [Using Ruby on Rails]
A series of flow of table creation → record creation, deletion → table deletion in Ruby on Rails
Escape processing when creating a URL in Ruby
Recommendation of Service class in Ruby on Rails
Rails new in Ruby on Rails ~ Memorandum until deployment 2
Ruby on Rails ~ Basics of MVC and Router ~
Introducing Rspec, a Ruby on Rails test framework
[Ruby on Rails] A memorandum of layout templates
Rails new in Ruby on Rails ~ Memorandum until deployment 1
[Ruby on Rails] How to install Bootstrap in Rails
I made a portfolio with Ruby On Rails
Notes on creating a many-to-many Factory with Rspec and testing it with SystemSpec [RSpec, FactoryBot]
[Introduction] Try to create a Ruby on Rails application
Ruby on Rails Incorrect string value error resolution when posting a form in Japanese
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Build a Ruby on Rails development environment on AWS Cloud9
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (5)
Write a class in Kotlin and call it in Java
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (6)
[Ruby On Rails] How to reset DB in Heroku
Ruby on Rails Elementary
Ruby on Rails basics
[Ruby on Rails] Post image preview function in refile
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (3)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (2)
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (1)
Ruby On Rails Association
[Rails AWS Docker] Build an existing Ruby on Rails + MySQL application with Docker and deploy it on AWS (4)
[Ruby on Rails] From MySQL construction to database change
[Rails] How to load JavaScript in a specific view
Explanation of Ruby on rails for beginners ② ~ Creating links ~
(Ruby on Rails6) How to create models and tables
[Ruby On Rails] De-root_path! Redirect notation from a nested "child" view to a nested "parent": show
Beginners write! Until you install postgreSQL on macOS catalina and make it available in rails 6.0.3.2
Click the [rails] button to create a random alphanumeric password and enter it in the password field
Problems and solutions while creating index.html.erb in RubyOnRails 4 on Windows 10
Definitely useful! Debug code for development in Ruby on Rails
[Ruby on Rails] Add a column with a foreign key constraint
[Ruby on Rails] Quickly display the page title in the browser
Rails: I've summarized the model and database for a moment.
(Ruby on Rails6) Display of the database that got the id of the database
A note about the seed function of Ruby on Rails
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
[Rails] How to display information stored in the database in view
[Ruby on Rails] Infinite scrolling using gem kaminari and jscroll
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails