0
0

More than 3 years have passed since last update.

[rails]dbの情報を表示する方法

Last updated at Posted at 2020-09-04

やりたいこと
Itemテーブルの情報を全て抜き出す
ビューファイルindex.html.erbにデーターベースの情報を表示させる

前提
Itemテーブルの内容infoカラムがある!
infoカラムのに保存した内容を表示させたい

①items_controllerに記述

 def index
    @items = Item.all
  end

解説

indexアクションが動いた時
@itemsにItemテーブル全ての情報が入るようにする。

②index.html.erbファイルに記述

<% @items.each do |item| %>
<%= item.info%>
<%end%>

解説

<% @items.each do |item| %>
@items←Itemテーブル全ての情報が入っている。
そこから中身の情報を全て抜き出してitem(変数)に一つずつ代入していく
<%= item.info%>
infoカラムに保存した情報
<%= %>
イコールをつけることによって情報を表示させることができる

Itemテーブルの内容
info
説明1
説明2

index.html.erbのビュー
説明1
説明2
(infoカラムに保存された情報が表示)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0