この記事の概要
・RubyonRailsについて、Progateで学んだことを書き記す
・ガチ初心者によるもの
・主に備忘録として、随時書き足していく
項目
環境情報
・Introduceモデルがある。中身は、
class Introduce < ApplicationRecord //saveメソッドが使えるクラスを継承している
end
・introducesテーブルがある。カラムは、
- id
- content
- created_at
- updated_at
データベースへのinsert
※rails consoleという、Railsが使えるディレクトリにおいて起動することで、Rubyを実行できるツールを用いている
実際の開発では別途、Controller内でModelにアクセスするような記述が必要なのではないか?要確認
rails console
intro = Introduce.new(content:"My name is Tanaka") //contentが"My name is Tanaka"であるIntroduceインスタンスを作成
intro.save //introインスタンスをテーブルに保存
結果)データベースのintroducesテーブルに、レコードが追加される
データベースからのSELECT
intro = Introduce.first //Introducesテーブルの一番目のレコードを取得し、変数に代入
intro.content //Introducesテーブルのcontentを表示
=>"My name is Tanaka"
intro = Introduce.all //Introducesテーブルのレコードを全件取得し、変数に代入
Introduce.all[0].content //Introducesテーブルの0番目のレコードのcontentを取得
データベースからSELECTしたデータを一覧表示
//Controller
def index
@introduces = Introduce.all //Introduceテーブルのレコードを全件取得
end
//index.html.erb
<% @introduces.each do |intro|%>
<%= intro.content %> //レコードの中のcontentの値をeachで全件表示