Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | Modelの生成とmigrationの実行

概要

Modelの生成

内容

Railsの自動生成機能でModelを生成します。

rails g model model_name カラム名:データ型 カラム名:データ型 ・・・

サンプル

自動生成実行

RSpecHaml環境です。デフォルト構成ならTest,ERBが生成されます

$ rails g model product name:string price:integer
    invoke  active_record
    create    db/migrate/20130709144049_create_products.rb
    create    app/models/product.rb
    invoke    rspec
    create      spec/models/product_spec.rb
生成内容

product.rb

class Product < ActiveRecord::Base
end

db/migrate/20130709144049_create_products.rb

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.integer :price

      t.timestamps
    end
  end
end
migrationの実行

DBの作成

rake db:create

migrationの実行(今回はproductテーブルが作成される)

rake db:migration
mySQLでmigrationされたテーブルを確認
mysql> desc products;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| price      | int(11)      | YES  |     | NULL    |                |
| created_at | datetime     | YES  |     | NULL    |                |
| updated_at | datetime     | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+