ポリモーフィック関連について、今回は解説します。
まず、ポリモーフィック関連とは、以下の図に示すように、type によってリレーション先の親モデルが変わるようなものと子の関係です。

Rails では、***_id (int)と、***_type (string(255)) によって、これを実現しています。
このようなデザインのDB設計をしてる場合の、MigrationファイルやModelの作成方法は以下のようになります。
① ポリモーフィック関連のテーブルのMigrationファイル
- class CreateItems < ActiveRecord::Migration
- def change
- create_table :items do |t|
- t.references :itemable, :polymorphic => true # この部分
- end
- end
- end
② ポリモーフィック関連のModel
Itemモデル
- # Item Model
- class Item < ActiveRecord::Base
- belongs_to :itemable, :polymorphic => true # この部分
- end
- # Restaurant Model
- class Restaurant < ActiveRecord::Base
- has_many :items, :as => :itemable # この部分
- end
- # Store Model
- class Store < ActiveRecord::Base
- has_many :items, :as => :itemable # この部分
- end
このように、itemable というポリモーフィック関連用のモデルのようなものを定義し、そいつに対して子と親からリレーションを張る感じです。
その際に、子には :polymorphic => true, 親には :as => :itemable を記述します。
③ ポリモーフィック関連のFixture
次に、テストデータの作成のために。Fixtureファイルの記述法を書きます。(以下)
- item1:
- itemable: store1 (Store)
- item2:
- itemable: restaurant1 (Restaurant)
これでOKです。