Wednesday, February 8, 2012

多重变异:Rails的Polymorphic和has_many :through实作

在创建现实的Model时,我们常常会遇到可运用在多方面的,例如Category,一个Product需要,一个Business Partner Entity也需要,因为Business Partner可以为Vendor, Customer, Banker等等。

# 创建Model
rails g model category name:string
rails g model categorization category:references categorizable_id:integer categorizable_type:string
rails g scaffold product name:string description:string
rails g scaffold business_partner name:string description:string
rake db:migrate

class Categorization < ActiveRecord::Base
  belongs_to :categorizable, :polymorphic => true
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :products, :through => :categorizations, :source => :categorizable, :source_type => 'Product'
  has_many :business_partners, :through => :categorizations, :source => :categorizable, :source_type => 'BusinessPartner'
end

class Product < ActiveRecord::Base
  has_many :categorizations, :as => :categorizable
  has_many :categories, :through => :categorizations
end

class BusinessPartner < ActiveRecord::Base
  has_many :categorizations, :as => :categorizable
  has_many :categories, :through => :categorizations
end

这样我们就可以使用rails所提供的方便语法来进行资料的操作。
product.categories, business_partner.categories, category.products and category.business_partners