1 class Parts < ActiveRecord::Base # STI 2 end 3 4 class Parts::Ima ge < 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.s
1 Parts::Image.store_full_sti_class # => true 2 Parts::Image.sti_name # => "Parts::Ima ge" 3 Parts::Image.create[:type] # => "Parts::Ima ge" 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
maiha
on Fri 8 Aug 2008
at 13:35