# 创建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