日報

ActiveRecord

18.1 外部キーの作成

マイグレーションで外部キー制約を付与することは可能です。
しかし
Railsでは外部キーを扱う場合に「DBテーブル自体に外部キー制約」は必要ありません

18.2 モデルにおけるリレーションシップの指定

1対1
  • has_one
  • belongs_to
1対多のリレーションシップ
  • has_many
多対多のリレーションシップ
  • has_and_belongs_to_many

18.3 belongs_toとhas_xxx宣言

belongs_to
  • product(force_reload=false)
  • product=obj
  • build_product(attributes=)
  • create_product(attributes=)
has_one宣言

オプション

  • :dependent=>:destroy(or true)
  • :dependent=>:nullify
  • :dependent=>false(or nil)
has_many宣言

メソッド

  • orders(force_reload=false)
  • orders<
  • orders.push(order1,,,)
  • orders.replace(order1,,,)
  • orders.delete(order1,,,)
  • orders.delete_all(
  • orders.destroy_all(
  • orders.clear
  • orders.find(options)
  • orders.count(options)
  • orders.size
  • orders.length
  • orders.empty?
  • orders.sum(options)
  • orders.unique
  • orders.build(attributes)
  • orders.create(attributes)
has_and_belongs_to_many宣言
結合テーブルとしてのモデルの使用
  • 重複の削除

has_manyにunique=>trueの適用

アソシエーションの拡張

has_manyに:throughオプションを適用

  • アソシエーションの拡張の共有

Rubyモジュールに拡張メソッドを記述し:extendパラメータでアソシエーション宣言に渡す

18.4 複合テーブルへの結合

ポリモーフィックアソシエーション、単一テーブル継承

単一テーブル継承
ポリモーフィックアソシエーション

18.5 自己参照結合

18.6 Act as

Act As List
Act As Tree

18.7 保存のタイミング

保存とコレクション

18.8 子行のプリロード

18.9 カウンタ