capsctrldays

2006-02-26 (日) [長年日記]

[Rails] クラスチェンンジ

読書会で継承のクラスチェンジできるお、みたいなことを言ってみたものの、 よく分からなかったので試してみた。Railsのインストールからやる羽目に(うあー)。

こんなモデルがあります。

class Customer < ActiveRecord::Base
  def hello
  end
end

class NormalCustomer < Customer
  def hello
    "hello, I'm normal"
  end
end

class SuperCustomer < Customer
  def hello
    "hello, I'm super"
  end
end

NormalCustomer作るお。

>> c1 = NormalCustomer.new
=> #<NormalCustomer:0x397def8 @attributes={"name"=>"", "type"=>"NormalCustomer"}, @ne
w_record=true>
>> c1.hello
=> "hello, I'm normal"

typeフィールドを変更してみるお。

>> c1.type = 'SuperCustomer'
=> "SuperCustomer"

でもまだNormalCustomerだお。

>> c1.hello
=> "hello, I'm normal"
>> c1.save
=> true
>> c1.hello
=> "hello, I'm normal"

なので、reloadしてみるお。

>> c1.reload
ActiveRecord::RecordNotFound: Couldn't find NormalCustomer with ID=1
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/bas
e.rb:412:in `find'
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/bas
e.rb:1309:in `reload'
        from (irb):8

がーん。

なので、またfindしてみる。

>> c1 = Customer.find(c1.id)
=> #<SuperCustomer:0x3907980 @attributes={"name"=>"", "type"=>"SuperCustomer", "id"=>
"1"}>
>> c1.hello
=> "hello, I'm super"

他にやり方あるのかな。

base.rb見てみる。

# Reloads the attributes of this object from the database.
def reload
  clear_aggregation_cache
  clear_association_cache
  @attributes.update(self.class.find(self.id).instance_variable_get('@attributes'))
  self
end

これじゃ、サブクラスだとreloadが使えない。

本日のツッコミ(全3件) [ツッコミを入れる]
1 logotip (2006-05-20 (土) 22:58)

Female wrestling ! Perfect! http://blogs.ya.com/espozito/files/wrestling.html female wrestling

2 lamborgi (2006-06-22 (木) 09:18)

Soma carisoprodol - MedlinePlus Drug Information: Carisoprodol http://blog.azpoint.net/blog/carispa soma carisoprodol

3 laja (2006-06-22 (木) 20:03)

http://blog.azpoint.net/blog/paxa buy paxil