金子邦彦研究室プログラミングRuby による Web/データベース・プログラミングJRuby で Ruby on Rails バージョン 3 を使ってみる

JRuby で Ruby on Rails バージョン 3 を使ってみる

Ruby on Rails バージョン 3 を使ってみる.

【関係するディレクトリとファイル(主要なもの)】

この Web ページで行うこと

  1. Rails アプリケーションのディレクトリと基本ファイルの生成

    データベース管理システムソフトウェアとして SQLite バージョン 3を使うとき

    cd <全体のルートディレクトリ>
    rails new hoge --database sqlite3
    
  2. コントローラの作成
    1. rails generate controller の実行
      cd hoge
      rails generate controller welcome index
      
    2. 上の操作の後,app/views/welcome/index.html.erb を編集
    3. public/index.html を削除
      rm public/index.html 
      
    4. config/routes.rb を次のように編集し、welcome/index.html.erb を使うように設定

      元々の config/routes.rb の記述に従って編集する。

      ■ パターン1

      root 'welcome#index'
      

      [image]

      ■ パターン2

      root :to => 'welcome#index'
      

      [image]
  3. Rails アプリケーションのひな形 (scaffold アプリケーション) の生成
    cd hoge
    rails generate scaffold order_record year:integer month:integer day:integer customer_name:text product_name:text unit_price:float qty:integer created_at:timestamp updated_at:timestamp
    
  4. (オプション) マイグレーション・ファイルでのテーブル定義に制約を追加

    ファイル cc/migrate/<タイムスタンプ>_create_order_records.rb を編集する

    SQLite 3 でのマイグレーション・ファイルの設定例:

    class CreateOrderRecords < ActiveRecord::Migration
      def change
        create_table :order_records do |t|
          t.integer :year,            :null => false
          t.integer :month,            :null => false
          t.integer :day,            :null => false
          t.text :customer_name,    :null => false
          t.text :product_name,    :null => false
          t.float :unit_price,    :null => false
          t.integer :qty,            :null => false, :default => 1
          t.timestamp :created_at,  :null => false
          t.timestamp :updated_at
    
          t.timestamps
        end
      end
    end
    

    SQLite 3 以外でのマイグレーション・ファイルの設定例:

    class CreateOrderRecords < ActiveRecord::Migration
      def change
        create_table :order_records do |t|
          t.integer :year,            :null => false
          t.integer :month,            :null => false
          t.integer :day,            :null => false
          t.text :customer_name,    :null => false
          t.text :product_name,    :null => false
          t.float :unit_price,    :null => false
          t.integer :qty,            :null => false, :default => 1
          t.timestamp :created_at,  :null => false
          t.timestamp :updated_at
    
          t.timestamps
        end
    
    
        #add constraints
        execute "ALTER TABLE order_records ADD CONSTRAINT c1_order_records CHECK ( year > 2008 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c2_order_records CHECK ( month >= 1 AND month <= 12 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c3_order_records CHECK ( day >= 1 AND day <= 31 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c4_order_records CHECK ( unit_price > 0 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c5_order_records CHECK ( qty > 0 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c6_order_records CHECK ( ( unit_price * qty ) < 200000 );"
    
      end
    end
    
  5. リレーショナルデータベースの作成
    rake db:create:all
    rake db:migrate
    
  6. Rails サーバの起動
    rails server
    
  7. 動作確認

    http://localhost:3000/order_records

[このページで説明している.こと]

前準備

  1. JRuby を使うので,Windows での Java JDK 18 (Java SE Development Kit 18) のインストールが済んでいること.
  2. JRuby のインストールが終わっていること

    (参考)Ubuntu でのインストール手順

    sudo apt -y update
    sudo apt -y install rbenv 
    sudo apt -y install git
    git clone https://github.com/sstephenson/rbenv.git .rbenv 
    #
    cd /tmp
    git clone https://github.com/sstephenson/ruby-build.git
    cd ruby-build
    sudo ./install.sh
    #
    export PATH="${HOME}/.rbenv/shims:/home/ubuntuuser/.rbenv/bin:${PATH}"
    eval "$(rbenv init -)"
    #
    fgrep -v rbenv ${HOME}/.bashrc > /tmp/bashrc.$$ 
    sudo cp /tmp/bashrc.$$  ${HOME}/.bashrc
    sudo chown ubuntuuser ${HOME}/.bashrc
    # 
    echo "export PATH=\"${HOME}/.rbenv/shims:/home/ubuntuuser/.rbenv/bin:${PATH}\"" >> ${HOME}/.bashrc
    echo 'eval "$(rbenv init -)"' >> ${HOME}/.bashrc
    #
    rbenv install jruby-1.7.3
    echo 'rbenv global jruby-1.7.3' >> ${HOME}/.bashrc
    sudo chown ubuntuuser ${HOME}/.bashrc
    source ${HOME}/.bashrc
    #
    gem install --no-ri --no-rdoc --clear-sources rbenv-rehash 
    
  3. gem を使って Rails 関連パッケージのインストールが終わっていること
    gem install rails 
    gem install exexjs
    gem install therubyracer
    gem install sqlite3
    

前もって決めておく事項

Rails アプリケーションのディレクトリと基本ファイルの生成

  1. rails コマンド による Rails アプリケーションのディレクトリと基本ファイルの生成

    rails バージョン 3 の場合の例

    cd <全体のルートディレクトリ>
    rails new hoge --database sqlite3
    

    [image]
    [image]

    なお、データベース管理システムソフトウェアとして MySQL の利用 を使うときは、次のように操作する

    cd <全体のルートディレクトリ>
    rails new hoge --database mysql
    
  2. (オプション)データベース設定ファイル config/database.yml の確認

    既定(デフォルト)では,SQLite 3 が使われることが確認できる. この Web ページの目的である Ruby on Rails の入門用)としては全く問題ない.

    データベース名も確認できる.

    ※ MySQL などを使うときは,database.yml にパスワードを設定する

    Ubuntu での実行例

    cd hoge
    more config/database.yml
    

    [image]
  3. 確認

    Rails サーバを起動し、動作を確認する

    1. Rails サーバの起動
      cd hoge
      rails server 
      

      [image]
    2. Web ブラウザから使ってみる

      http://localhost:3000

      [image]
    3. Rails サーバの停止

      Rails サーバを起動した端末で「コントロールキー」と「c」の同時押し

      [image]

コントローラの作成

  1. rails generate controller の実行
    cd hoge
    rails generate controller welcome index
    

    [image]
  2. 上の操作の後,app/views/welcome/index.html.erb を編集

    [image]
  3. public/index.html を削除

    [image]
  4. config/routes.rb を次のように編集し、welcome/index.html.erb を使うように設定

    元々の config/routes.rb の記述に従って編集する。

    ■ パターン1

    cd hoge
    root 'welcome#index'
    

    [image]

    ■ パターン2

    cd hoge
    root :to=>'welcome#index'
    

    [image]
  5. config/routes.rb の設定確認

    「rake routes」で確認する.

    rake routes
    

    [image]

Rails アプリケーションのひな形 (scaffold アプリケーション) の生成

前もって決めておく事項

rails generate scaffold の実行

  1. 先ほど生成した Rails アプリケーションのルートディレクトリに,カレントディレクトリを変更

    cd hoge
    

    [image]
  2. (オプション) bundle install の実行

    実行例

    bundle install 
    

    [image]
  3. rails generate scaffold order_record ...」を実行し、アプリケーションのひな形を生成する

    rails generate scaffold order_record year:integer month:integer day:integer customer_name:text product_name:text unit_price:float qty:integer created_at:timestamp updated_at:timestamp
    

    [image]

    【ここで試している設定の要点】

    Rails で使えるデータ型は次の通り

    データ型の詳細については,別の Web ページで説明する.

    ※ execjs を使っている場合,次のようなエラーが出る場合があります.このときは、node.js などをインストールすることで回避できる場合があります. 詳しくは、 https://github.com/sstephenson/execjs

    [image]

    Windows の場合には「/」を「\」に読み替えて下さい.

    Windows で「sqlite3.dll が無いよ」というエラーが出た場合には SQLite 3のサイト から sqlite3.dll をダウンロードして,C:\Windows\System32 に置く

    [image]
  4. 「rake routes」で確認
    rake routes
    

    [image]

マイグレーション・ファイルでのテーブル定義

マイグレーション定義ファイルには,データベースのテーブル定義と一貫性制約の記述等を行う.

関連する外部ページ

https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html

  1. Rails アプリケーションのひな形の作成において生成されたマイグレーション・ファイルの確認

    マイグレーション・ファイルを表示させる手順の例は次の通り.20130510014046は実際の日付に読み替えてください.

    ■ Linux での実行例

    more cc/migrate/20130510014046_create_order_records.rb
    

    [image]

    Windows の場合には「/」を「\」に読み替えて下さい.

  2. マイグレーション・ファイルでのテーブル定義と一貫性制約の記述

    いま確認したマイグレーション・ファイルを書き換えて,一貫性制約を記述したい.

    記述したい一貫性制約は,SQL を使って次のように書くことができるとする.問題は,これを,マイグレーション・ファイルにどう書くか,ということ.

    SQL の文法と意味については,ここでは説明しないので, 別の Web ページを見てください.

    一貫性制約を含むテーブル定義の例 (SQL での記述)

    このページでは,次のテーブル定義を使う.

    SQLite 3 の場合:

    create table order_records (
        id            INTEGER  PRIMARY KEY autoincrement not null,
        year          INTEGER  not null,
        month         INTEGER  not null,
        day           INTEGER  not null,
        customer_name text  not null,
        product_name  text  not null,
        unit_price    REAL     not null,
        qty           INTEGER  not null DEFAULT 1,
        created_at    DATETIME not null,
        updated_at    DATETIME not null);
    

    SQLite 3以外 の場合:

    create table order_records (
        id            INTEGER  PRIMARY KEY autoincrement not null,
        year          INTEGER  not null CHECK ( year > 2008 ),
        month         INTEGER  not null CHECK ( month >= 1 AND month <= 12 ),
        day           INTEGER  not null CHECK ( day >= 1 AND day <= 31 ),
        customer_name text  not null,
        product_name  text  not null,
        unit_price    REAL     not null CHECK ( unit_price > 0 ),
        qty           INTEGER  not null DEFAULT 1 CHECK ( qty > 0 ),
        created_at    DATETIME not null,
        updated_at    DATETIME not null,
        CHECK ( ( unit_price * qty ) < 200000 ) );
    

    ◆ ここで行うこと: 上記のテーブル定義と等価なものをマイグレーション・ファイルに記述したいということ

    SQLite 3 でのマイグレーション・ファイルの設定例:

    class CreateOrderRecords < ActiveRecord::Migration
      def change
        create_table :order_records do |t|
          t.integer :year,            :null => false
          t.integer :month,            :null => false
          t.integer :day,            :null => false
          t.text :customer_name,    :null => false
          t.text :product_name,    :null => false
          t.float :unit_price,    :null => false
          t.integer :qty,            :null => false, :default => 1
          t.timestamp :created_at,  :null => false
          t.timestamp :updated_at
    
          t.timestamps
        end
      end
    end
    

    SQLite 3 以外でのマイグレーション・ファイルの設定例:

    http://guides.rails.info/migrations.html の記述によれば, マイグレーション・ファイル内に execute ... を含めることになる.実例を下に載せています.

    SQLite 3 には ADD CONSTRAINT の機能が実装されていないため、下のプログラムは動かない(2011/09/01 時点).

    class CreateOrderRecords < ActiveRecord::Migration
      def change
        create_table :order_records do |t|
          t.integer :year,            :null => false
          t.integer :month,            :null => false
          t.integer :day,            :null => false
          t.text :customer_name,    :null => false
          t.text :product_name,    :null => false
          t.float :unit_price,    :null => false
          t.integer :qty,            :null => false, :default => 1
          t.timestamp :created_at,  :null => false
          t.timestamp :updated_at
    
          t.timestamps
        end
    
    
        #add constraints
        execute "ALTER TABLE order_records ADD CONSTRAINT c1_order_records CHECK ( year > 2008 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c2_order_records CHECK ( month >= 1 AND month <= 12 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c3_order_records CHECK ( day >= 1 AND day <= 31 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c4_order_records CHECK ( unit_price > 0 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c5_order_records CHECK ( qty > 0 );"
        execute "ALTER TABLE order_records ADD CONSTRAINT c6_order_records CHECK ( ( unit_price * qty ) < 200000 );"
    
      end
    end
    

リレーショナルデータベースの作成

  1. 先ほど生成した Rails アプリケーションのルートディレクトリに,カレントディレクトリを変更

    cd hoge
    

    [image]
  2. (オプション)rake で実行可能なタスク一覧の表示

    rake -T
    

    [image]
  3. (オプション)データベース・スキーマの版(バージョン)の確認

    rake db:version
    

    [image]
  4. データベース・マイグレーションの実行によるデータベースの生成

    rake db:create:all
    

    [image]
  5. マイグレーション・ファイルと rake コマンドを用いたマイグレーションの実行

    メッセージから,新しいテーブルが定義されたことが分かります.

    rake db:migrate
    

    [image]
  6. テーブル定義の確認

    「"id" integer primary key autoincrement not null」が増えていることなどが確認できる.

    echo "select * from sqlite_master;" | sqlite3 db/development.sqlite3 
    

    [image]

Rails サーバの起動と動作確認

  1. 先ほど生成した Rails アプリケーションのルートディレクトリに,カレントディレクトリを変更

    cd hoge
    

    [image]
  2. Rails サーバの起動

    rails server
    

    [image]

    WEBrick が起動していることが確認できる.ポート番号が 3000 であることも確認できる.

  3. Rails サーバと通信できることのテスト

    Web ブラウザで http://127.0.0.1:3000 を指定します.

    この Web ページの「コントローラの作成」の手順を踏んでいた場合には, Rails サーバと通信して,welcome/index.html.erb が次のように表示される

    [image]

    Windows のファイヤウオール機能により,ポート番号 3000 との通信が遮断されている場合があるので, ポート番号 3000 の通信については解除しておくこと.

  4. Ctrl + 「c」 による Rails サーバの終了

    Ctrl + 「c」(コントロールキーと「c」キーの同時押し)で,Rails サーバが終了します.

    [image]
  5. Rails コマンドの確認

    rails
    

    [image]

scaffold アプリケーションを使ってみる

以下の手順では,いま生成された scaffold アプリケーションを使ってみる.

  1. http://127.0.0.1:3000/order_records を Web ブラウザで開く
  2. New order_record をクリック

    [image]
  3. 新しいウインドウが開く.これは,テーブルに新しい行(レコード)を挿入するための編集画面

    [image]
  4. データを設定し,Create order_record をクリック

    [image]

    ※ もし,どれかのフィールドのデータが空 (NULL) のままだと,テーブル定義で指定した not null 制約に違反し,行(レコード)を挿入できない.

  5. 行(レコード)挿入の確認

    間違いがあるときは「Edit」で編集画面に戻る.

    [image]

    [image]

    ◆ これで正しいときは「Back」で元の画面に戻る.

  6. Back をクリックすると,元の画面に戻る.order_records テーブルに行(レコード)が挿入されたことが確認できる.

    [image]
  7. Show」をクリックすると,1ページで1レコード表示される.

    [image]

    [image]
  8. Edit」をクリックすると,編集画面に移る

    [image]
  9. Delete」をクリックすると,削除される

    [image]
  10. 今度は日本語を試してみる

    # 「① ② I Ⅱ ㍉ ㌢ ㈱」は Shift_JIS にはなく,Shift_JIS を拡張した文字コードセットにある
    # 「‖ 〜 − ¢ £ ¬」は Shift_JIS, EUC-JP, ISO-2022-JP では同じ文字コードなのに Windows-31J では違う文字コード
    # 「表 十 構」は、Shift_JIS では 2 バイト目が「5C」になっているもの
    #  その他 "〒" ハンカクカナ
    

    [image]
  11. 確認表示

    [image]