memo

model/ActiveRecord

作成・削除

modelで指定可能なデータ型

マイグレーション

MySQLでの型指定

class CreateTest < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.integer :status, limit: 1
    end
  end
end
   
TINYINT 1
SMALLINT 2
MEDIUMINT 3
INT 4〜6
BIGINT 5〜8
Migration MySQL Ruby
integer int(11) Fixnum
decimal decimal(10,0) BigDecimal
float float Float
string varchar(255) String
text text String
binary blob String
date date Date
datetime datetime Time
timestamp datetime Time
time time Time
boolean tinyint(1) TrueClass/FalseClass

Association

多対多

(例)
Customer -> Order -> Item
青文字は Customer から Item を参照するために設定
背景黄色は Item から Customer を参照するために追加設定
Customer

class Customer < ActiveRecord::Base
 has_many :orders                     // Customer => Item
 has_many :items, through: :orders    // Customer => Item

 scope :has_item_id, -> item_id {              // Item => Customer
 joins(:items).where('items.id = ?', item_id)  // Item => Customer
 }
end

Order

class Order < ActiveRecord::Base
  belongs_to :customer  // Customer => Item
  belongs_to :item      // Customer => Item
end

Item

class Item < ActiveRecord::Base
  has_many :orders                        // Customer => Item
  has_many :customers, through: :orders   // Customer => Item
  delegate :customer, to: :order          // Item => Customer
end

Validator