RAILS PRESS RUBY on RAILS, it’s DRY and COOL …

RSS Feed

RAILS PRESS RSS

Tag Cloud

はてなブックマーク - railspress.matake.jp の注目エントリー
象形文字くさび形文字ミイラそろばんの玉そろばんコーラン占いの板?象牙大英博物館
« 前のエントリ
Rails2.0ではActionMailer::Base.server_settingsは使えない
次のエントリー »
acts_as_bits PluginとRails 2.1のDirty tracking & Partial Updatesの相性が最悪

Posted on
2008/06/14

Tags
ActiveRecord, Single Table Inheritance, ノウハウ

Keywords


この記事をはてなブックマークに登録 この記事のはてなブックマーク数 この記事を livedoor クリップに登録この記事の livedoor クリップ数 このエントリを del.icio.us に追加
ブックマークに追加する

単一テーブル継承 (Single Table Inheritance) の上手な扱い方

Railsの単一テーブル継承 (Single Table Inheritance) を使うと、ActiveRecordではtypeカラムがnilでないオブジェクトのクラスはtypeを元に判定されます。

単一テーブル継承 (Single Table Inheritance) を使うには、テーブル定義時にtypeというカラムを定義します。

LANG : RUBY
  1. class CreatePeople <ActiveRecord::Migration
  2.   def self.up
  3.     create_table :people do |t|
  4.       t.column :name, :string
  5.         :
  6.       t.column :type, :string
  7.     end
  8.   end
  9.  
  10.   def self.down
  11.     drop_table :people
  12.   end
  13. end

ここでpeopleテーブルに対応したPersonというベースとなくクラスを以下のように定義したとします。

LANG : RUBY
  1. class Person <ActiveRecord::Base
  2.   # edit here
  3. end

こうするとPersonを継承したモデルは全てpeopleテーブルに保存され、typeカラムに各モデルのクラス名が入ります。

(単一テーブル継承の詳しい使い方はこちらをご覧ください:「Railsで単一テーブル継承(Single Table Inheritance) | 京の路」)

ここで、実際には利用しない中間クラスを挟むと、Personのサブクラスへのアクセスをそのクラスに集中させることで、各サブクラスのクラスを意識することなく扱うことができるようになります。

例えばExtendedPersonクラスを中間クラスとして挟み、ExtendedPersonを継承したMale / Femaleというモデルを定義します。

LANG : RUBY
  1. class Student <Person
  2.   # edit here
  3. end
  4.  
  5. class MaleStudent <Student
  6.   def call_name
  7.     "#{name}くん"
  8.   end
  9. end
  10.  
  11. class FemaleStudent <Student
  12.   def call_name
  13.     "#{name}さん"
  14.   end
  15. end

こうすると、以下のようにMale / Femaleを意識することなく、これらのインスタンスを扱えます。

LANG : RUBY
  1. MaleStudent.create(:name => "タロウ")
  2. MaleStudent.create(:name => "ハナコ")
  3.  
  4. students = Student.find(:all)
  5. students.each do |student|
  6.   student.call_name
  7. end
  8.  
  9. # =>
  10. #  タロウくん
  11. #  ハナコさん

もうこんなことしなくていい。

LANG : RUBY
  1. male_students = MaleStudent.find(:all)
  2. female_students = FemaleStudent.find(:all)
  3.  
  4. male_students.each do |male_student|
  5.   male_student.call_name
  6. end
  7.  
  8. female_students.each do |female_student|
  9.   female_student.call_name
  10. end

単一テーブル継承で多数のクラスを1つのテーブルに集中させる場合は、これでソースがかなり奇麗になりますよ♪


この記事がお役に立ちましたら、一言コメントもらえると嬉しいですm_ _m


コメントはこちらから




使用可能タグ: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


« 前のエントリ
Rails2.0ではActionMailer::Base.server_settingsは使えない
次のエントリー »
acts_as_bits PluginとRails 2.1のDirty tracking & Partial Updatesの相性が最悪