LoginSignup
0
0

More than 3 years have passed since last update.

【RubyOnRails】テーブル操作(insert,select)

Last updated at Posted at 2019-09-25

この記事の概要

・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で全件表示
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