8
9

More than 5 years have passed since last update.

Railsでのsqliteの基本操作

Last updated at Posted at 2019-06-25

超基本操作

--コンソールの起動--

$ rails dbconsole

--テーブルの確認--

sqlite> .tables

--スキーマの確認--

sqlite> .schema

--文字列を検索

sqlite> select * from lists where address like '京都府%';

--項目に予約語を使ってしまった場合のSQL

select * from wards where "order"=13;

テーブル(model付き)の作成-----

--1.コマンドを実行(モデル名は頭大文字の単数形)

$ rails generate model Shop url:string name:string price:string surl:string area:string service:string copy:string comment:string time:string tel:string

--2.マイグレーション

rake db:migrate

テーブルのカラムの追加・削除

rails g migrationでファイルを作成して、rails db:migration でDBに反映させる流れ

--カラムの追加--

rails g migration[Addカラム名Toテーブル名] [カラム名:型]
※Addの後のカラム名とテーブル名の表記に注意
※カラム名にしてはいけないワード[img]

$ rails g migration AddSurlToLists surl:string
$ rake db:migrate

---カラムの変更--

都道府県テーブル(prefectures)の地域カラム(area)をintegerからstringに変更する

マイグレーションファイルを作成する

$rails g migration change_prefectures_area_string

マイグレーションファイルを編集する

20190724_change_prefectures_area_string.rb
class ChangePrefecturesAreaString < ActiveRecord::Migration[5.0]
  def change
    change_column :prefectures, :area, :string
  end
end

反映させる

$ rails db:migrate

---カラムの削除--

$ rails g migration RemoveAreaFromLists area:int
$ rake db:migrate

---テーブル削除-----

マイグレーションファイルの作成

テーブルを削除するためのマイグレーションファイルを作成する。

$ rails generate migration reviews

マイグレーションファイル編集

消したいテーブルを指定する

class DeleteRocords < ActiveRecord::Migration[5.1]
  def change
    drop_table :reviews
  end
end

下記のコマンドを叩くと、データベースから削除される。

$ rails db:migrate

データ型について

説明
string 字列
text 改行を含む長い文字列
integer 整数
float 浮動小数
decimal 精度の高い小数
datetime 日時
timestamp より細かい日時
time 時間
date 日付
binary バイナリデータ
boolean Boolean型

csvをテーブルにインポートする

別記事:https://qiita.com/ai_qiita/items/479e77dde88655930c83

8
9
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
8
9