2012-04-12 109 views
0

請幫助新手選擇在RoR3中實現繼承的最佳方式。我有:Ruby on Rails中的模型繼承3

 
-Person (address fields, birthdate, etc.) 
    -Player, inherits from Person (position, shoe_size, etc.) 
     -Goalkeeper, inherits from Player (other specific fields related to this role) 

我認爲單表繼承是一個不好的解決方案,因爲在創建的表中會有很多空字段。做這個的最好方式是什麼?使用多態關聯(with has_one?)?使用belongs_to/has_one(但是如何在Player視圖中顯示Person的字段?)?不要實現繼承?其他方案?

回答

1

雖然我認爲STI可能是我會用這個辦法,另外一個可能性,如果你想避免很多NULL屬性,是一列other_attributes添加到您的個人模式,將存儲屬性的Hash 。要做到這一點,一個text列添加到people表:

def self.up 
    add_column :people, :other_attributes, :text 
end 

然後確保屬性在模型序列化。你可能需要編寫一個包裝,以確保它初始化爲空Hash當您使用它:

class Person < ActiveRecord::Base 
    serialize :other_attributes 

    ... 

    def other_attributes 
    write_attribute(:other_attributes, {}) unless read_attribute(:other_attributes) 
    read_attribute(:other_attributes) 
    end 
end 

然後你可以使用屬性如下:

p = Person.new(...) 
p.other_attributes       #=> {} 
pl = Player.new(...) 
pl.other_attributes["position"] = "forward" 
pl.other_attributes       #=> {"position" => "forward"} 

一個警告這種方法在從other_attributes檢索數據時,應該使用字符串作爲鍵,因爲從數據庫中檢索Hash時,鍵總是字符串。