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

Sunday, June 15, 2008

夜深悼Kurt Cobain有感

狼是奇妙的動物:即合群,又兇残(只對獵物)

人,太複雜了。人即是社群动物,却也兇殘(任何種類)

狼的想法 - 跳躍性思考

迅速逮住猎物的必經之地,毫不猶豫的撲過去

狼與自然共存,狼明白,没了自然,就没有了它們

人也明白,只是口嫌言體正直(注1)而已

反而認為狼怎會明白?無非是造物者在創造它的時候注入了這些基因

太可悲了是不?當人想到這裡,也覺得自己很可悲

他没能力改變,只能順著基因走去,去品味,去創作

甚至,去喜欢自己喜欢的,去厭惡自己厭惡的

他想脫離,靠著酒精,毒品,麻醉

然却只能經過死亡的洗禮,逃脫,涅磐

槍聲響起,他化作一缕清魂(?)

是喜悦?还是痛苦?

他不知道,因为他早已没有了感覺

不是狼,也不是人,更不是狼人

一切皆空

悼年輕天才(注2) - Nirvana(涅磐)樂團的主唱Kurt Cobain



注1:
日語,嘴巴說不要,身體卻很老實

注2:
本來只是想寫自我介紹的,還有厘清一下自己最近閱讀的看法
沒想到寫一寫變成悼念Kurt Cobain去了
真糟糕,哈哈