前提
- Rails(前回の記事で手順を記載しています)
- DBに登録されたデータをControllerで取得し、Viewで表示するシンプルな内容になっています
Controllerを作成
-
rails g controller users index
でUsersControllerを作成- ApplicationControllerを継承しています

-
Hello, World
をブラウザに表示させます- renderの行を追記します
app/controller/users_controller.rb
class UsersController < ApplicationController
def index
render plain: 'Hello, World'
end
end
画面を表示
-
rails s
でサーバ起動- URLの末尾に
/users/index
を指定します
- URLの末尾に

ルーティングの変更
- URLとactionを紐付ける設定
config/routes.rbを以下の通り修正
- get 'users/index'
+ get 'users', to: "users#index"
- 画面を表示
- URLの末尾を
/users
に修正 - indexの指定が不要になりました
- URLの末尾を

Viewで表示
- MVCモデルに従い、Controllerから表示せずViewで表示するように修正します
viewファイルを修正
-
app/views/users/index.html.erb
を修正-
controller名/action名.html.erb
のルールになっています - 初期の記述は削除しています
-
app/views/users/index.html.erb
<p>Hello, View!</p>
- controllerを修正
- renderの行を削除しました
app/controller/users_controller.rb
class UsersController < ApplicationController
def index
end
end
- 画面を表示
- viewに記述した
Hello, View!
が表示されました
- viewに記述した

ControllerからViewに値を渡して表示する
app/controller/users_controller.rb
class UsersController < ApplicationController
def index
@message = "Hello, Controlller!"
end
end
app/views/users/index.html.erb
<p><%= @message %></p>

- Controllerでセットした
@message
の内容ををViewで表示しました
Modleを作成
-
rails g model User name:string age:integer
でUserModelを作成- 文字列型のname,数値型のageで構成されるモデル

- migrationファイルが自動生成されています
- ちなみに会社ではRidgepoleを採択しています、追々やります

- migrationを実行します
-
rails db:migrate
でマイグレーション実行 - DDLが実行されテーブルができます
-
rails dbconsole
でSQL操作ができるので、テーブル定義を確認しました - この後
tanaka
も作成しました
-


データベースの値を画面に表示します
- データを登録します(登録できれば下記方法ではなく、前述したdbconsoleからInsertするでも問題ないです)

- Contollerでusersテーブルのデータ全件を取得します
app/controller/users_controller.rb
class UsersController < ApplicationController
def index
@message = "Hello, Controlller!"
@users = User.all
end
end
- Viewで取得したusersのデータ全件を繰り返し出力します
app/views/users/index.html.erb
<p><%= @message %></p>
<ul>
<% @users.each do |user| %>
<li>
ID:<%= user.id %>, Name:<%= user.name %>, Age:<%= user.age %>
</li>
<% end %>
</ul>
- 画面にusersテーブルのデータが表示されました

最後に
- MVCモデルをとりあえず作りたかったため、とてもシンプルな構成になりました
- モデルを増やして、関連あたりも勉強していきたいですね
- やったことを順に手順化しただけなのでわかりにくい可能性あります、ご了承くださいませ