2012-04-12 22 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) 

と思います。これを行う最善の方法は何ですか?多態性の関連付けを使用する(has_one?)? belongs_to/has_oneを使用します(ただし、PlayerビューでPersonのフィールドも表示する方法は?)継承を実装しないでください。その他のソリューション?

答えて

1

私はSTIは、おそらく私は、これを一つの他の可能性を使用するアプローチだと思いますが、あなたがNULL属性の多くを回避したい場合は、属性のHashを保存するあなたの個人モデルに列other_attributesを追加することです。これを行うには、peopleテーブルにtext列を追加します。

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"} 

1回の警告をHashがデータベースから取得されたときにキーが常に文字列になるため、other_attributesからデータを取得するときに文字列をキーとして使用する必要があるということです。

0

私はSTIを推奨します。別の解決策は、mongodbのようなドキュメントストアを使用するか、アクティブレコードストアhttp://api.rubyonrails.org/classes/ActiveRecord/Store.htmlを使用することです。彼のHStore列http://rubygems.org/gems/activerecord-postgres-hstoreでpostgressデータベース見ている場合。

もう1つのオプションは、PostgreSQLのテーブル継承です。 http://www.postgresql.org/docs/8.1/static/ddl-inherit.html

関連する問題