1対多: belongs_to / has_many

関連

Customer (1) ←→ (n) Order

モデル

class Customer < ActiveRecord::Base
  has_many :orders # ← 複数形
end

class Order < ActiveRecord::Base
  belongs_to :customer # ← 単数形
end

belongs_to オプション

  • :autosave – 親オブジェクトが保存されるたびに、読み込まれているすべてのメンバを保存
  • :class_name – モデル名を直接指定
  • :counter_cache – 従属しているオブジェクトの数の検索効率の向上
  • :dependent – 関連付けられたオブジェクトの削除方法
    • :destroy – destroy メソッドは呼び出し
    • :delete – 直接削除
  • :foreign_key – 外部キーの名前を直接指定
  • :inverse_of – 逆関連付けとなる名前を指定
  • :polymorphic – true を指定すると、ポリモーフィック関連付けを指定
  • :touch – true に設定すると、関連オブジェクトの更新、削除をタイムスタンプに反映
  • :validate – true に設定すると、関連オブジェクトの保存時に必ず検証

has_many オプション

  • :as – ポリモーフィック関連付けであることを指定
  • :autosave – 親オブジェクトが保存されるたびに、読み込まれているすべてのメンバを保存
  • :class_name – モデル名を直接指定
  • :dependent – 関連付けられたオブジェクトの削除方法
    • :destroy – destroy メソッドは呼び出し
    • :delete – 直接削除
    • :nullify – NULL に設定
    • :restrict_with_exception – レコードが 1 つでもある場合に例外
    • :restrict_with_error – レコードが 1 つでも ある場合にエラー
  • :foreign_key – 外部キーの名前を直接指定
  • :inverse_of – 逆関連付けとなる名前を指定
  • :primary_key – 主キーを明示的に指定
  • :source – 関連付け元の名前を指定
  • :source_type – 関連付け元のタイプを指定
  • :through – 結合 (join) モデルを指定
  • :validate – true に設定すると、関連オブジェクトの保存時に必ず検証

マイグレーション

class CreateOrders < ActiveRecord::Migration
  def change
    create_table :customers do |t|
      t.string :name
      t.timestamps
    end

    create_table :orders do |t|
      t.belongs_to :customer # ← 単数形
      t.timestamps
    end
  end
end

コード

belongs_to

  • customer(force_reload = false) – 関連オブジェクトを返す
  • customer=(associate) – オブジェクトを関連付け
  • build_customer(attributes = {)} – オブジェクトをその オブジェクトに関連付け
  • create_customer(attributes = {)} – 関連オブジェクトを作成(保存あり)
  • create_customer!(attributes = {)} – 関連オブジェクトを作成(raise あり)

has_many

  • orders(force_reload = false) – 関連オブジェクトの配列
  • orders<<(object, …) – 1つ以上のオブジェクトをコレクションに追加
  • orders.delete(object, …) – 外部キーを NULL に設定し、1つまたは複数のオブジェクトを削除
  • orders.destroy(object, …) – destroy を実行し、1つまたは複数のオブジェクトを削除
  • orders=objects – コレクションの内容を置き換え
  • orders_singular_ids – コレクションのオブジェクトの id の配列
  • orders_singular_ids=ids – コレクションの内容を置き換え
  • orders.clear – すべてのオブジェクトを削除
  • orders.empty? – 関連付けられたオブジェクトがコレクションの中に1つもない場合に true
  • orders.size – オブジェクトの数
  • orders.find(…) – オブジェクトを検索
  • orders.where(…) – 指定された条件に基いて検索
  • orders.exists?(…) – 条件に合うオブジェクトが存在するかどうかをチェック
  • orders.build(attributes = {, …)} – オブジェクトをその オブジェクトに関連付け
  • orders.create(attributes = {)} – 関連オブジェクトを作成(保存あり)
  • orders.create!(attributes = {)} – 関連オブジェクトを作成(raise あり)

参照

確認バージョン

  • Rails 4.2.6
  • ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
カテゴリー: Association タグ: , パーマリンク

コメントは停止中です。