Ruby on Rails (3.x >= 3.2.9) のためのブログです (どっちかというと社内ブログ的な感じで、基礎から書いてきます) 。
12月
15
Comments


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



Rails では、***_id (int)と、***_type (string(255)) によって、これを実現しています。

このようなデザインのDB設計をしてる場合の、MigrationファイルやModelの作成方法は以下のようになります。

① ポリモーフィック関連のテーブルのMigrationファイル


  1. class CreateItems < ActiveRecord::Migration  
  2.   def change  
  3.     create_table :items do |t|  
  4.       t.references :itemable:polymorphic => true # この部分  
  5.     end  
  6.   end  
  7. end  

② ポリモーフィック関連のModel


Itemモデル
  1. # Item Model  
  2. class Item < ActiveRecord::Base  
  3.   belongs_to :itemable:polymorphic => true # この部分  
  4. end  
Restaurantモデル
  1. # Restaurant Model  
  2. class Restaurant < ActiveRecord::Base  
  3.   has_many :items:as => :itemable # この部分  
  4. end  
Storeモデル
  1. # Store Model  
  2. class Store < ActiveRecord::Base  
  3.   has_many :items:as => :itemable # この部分  
  4. end  

このように、itemable というポリモーフィック関連用のモデルのようなものを定義し、そいつに対して子と親からリレーションを張る感じです。
その際に、子には :polymorphic => true, 親には :as => :itemable を記述します。


③ ポリモーフィック関連のFixture


次に、テストデータの作成のために。Fixtureファイルの記述法を書きます。(以下)
  1. item1:  
  2.   itemable: store1 (Store)  
  3. item2:  
  4.   itemable: restaurant1 (Restaurant)  
※ store1 と restaurant1 のラベルが定義されている仮定です。


これでOKです。

Categories: , ,

Leave a Reply