• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

   1  class Parts < ActiveRecord::Base # STI
   2  end
   3  
   4  class Parts::Image < Parts
   5  end
   6  
   7  part = Parts::Image.create!
   8  p part[:type]

で何が返るのかの話。

before 2.1

   1  part[:type]  # => "Image"

after 2.1

   1  part[:type]  # => "Parts::Image"

互換性

2.1 では AR::Base.sti_name メソッドが返す値を利用しており、 AR::Base.store_full_sti_class で制御できる。

   1  Parts::Image.store_full_sti_class  # => true
   2  Parts::Image.sti_name              # => "Parts::Image"
   3  Parts::Image.create[:type]         # => "Parts::Image"
   4  
   5  Parts::Image.store_full_sti_class = false
   6  Parts::Image.sti_name              # => "Image"
   7  Parts::Image.create[:type]         # => "Image"

応用

2.1 のSTIを利用するとナベアツな世界を簡単に作成できる。

   1  class Person < ActiveRecord::Base; end
   2  class Nabe < Person; end
   3  class Aho < Person; end
   4  def Person.sti_name
   5    Time.now.day % 3 == 0 ? "Aho" : "Nabe"
   6  end
   7  
   8  (1..3).map{ Nabe.create[:type] }
   9  => ["Nabe", "Nabe", "Nabe"]
  10  
  11  # Stub
  12  class Time
  13    def day
  14      3
  15    end
  16  end
  17  
  18  (1..3).map{ Nabe.create[:type] }
  19  => ["Aho", "Aho", "Aho"]

posted by Png maiha on Fri 8 Aug 2008 at 13:35
Contents
Rails2.1 の STI
Comments
maiha: 追記)対応は約1営業日でした。チームの忙しさに応じて変動するとは思いますが、大体の目安情報とい... '10-4
maiha: なるほど。rails のログから実行したクエリを抜き出したいと思うことがよくありまして。 あ... '10-3
winebarrel: レポートありがとうございます。 削除できない件は修正しました。 SQLのparserはTC/... '10-2
maiha: なるほど。ありがとうございます! '10-2
ursm: Haml 2.2 以降はどこでも式展開が使えるようになったので、== は意味がなくなりました。... '10-2
Services from s21g
twpro(ツイプロ)
Twitterプロフィールを快適検索
地価2009
土地の値段を調べてみよう
MyRestaurant
自分だけのレストラン手帳
Formula
ブログに数式を埋め込める数式コミュニティ