『Rails Recipes』Part II Database Recipes知識点まとめ3


Polymorphic Associations—has_many :whatevers Problem
「Rails cookbook」の一節はこの章と似ている.
テーブル内の特定のプロパティによって異なるモデルのデータを区別してマルチステートを実現
データベース・コード

class AddPeopleCompanyAndAddressTables < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column :name, :string
end
create_table :companies do |t|
t.column :name, :string
end
create_table :addresses do |t|
t.column :street_address1, :string
t.column :street_address2, :string
t.column :city, :string
t.column :state, :string
t.column :country, :string
t.column :postal_code, :string
#               mode,hibernate        
t.column :addressable_id, :integer
t.column :addressable_type, :string
end
end
def self.down
drop_table :people
drop_table :companies
drop_table :addresses
end
end


モデル関係の設定

#  :as :polymorphic  
class Person < ActiveRecord::Base
has_many :addresses, :as => :addressable
end

class Company < ActiveRecord::Base
has_many :addresses, :as => :addressable
end


class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end