Changing an Object Class in ActiveRecord

Let's say I have an object FireNinja < Ninjain my database that is stored using unidirectional inheritance. Later I understand that he really is WaterNinja < Ninja. What is the cleanest way to change it to another subclass? Even better, I would like to create a new object WaterNinjaand just replace the old one FireNinjain the database, saving the identifier.

Edit I know how to create a new object WaterNinjafrom my existing one FireNinja, and I also know that I can delete the old one and save the new one. What I would like to do is change the class of an existing element. I do this by creating a new object and doing ActiveRecord magic to replace the string or doing some crazy thing for the object itself or even deleting it and reinserting it with the same identifier, although this is part of the question.

+5
source share
4 answers

You need to do two things:

  • Create WaterNinja < Ninja
  • In the table, ninjasrun something likeUPDATE ninjas SET (type = 'WaterNinja') WHERE (type = 'FireNinja')

What about that.

To do the runtime conversion, this will do, but I do not recommend.

class Ninja
  def become_another_ninja(new_ninja_type)
    update_attribute(:type, new_ninja_type)
    self.class.find(id)
  end
end

@water_ninja = @fire_ninja.become_another_ninja('WaterNinja')

, @fire_ninja .

+2

FireNinja WaterNinja,

@ninja.becomes(WaterNinja)

, type.

@ninja.type = "WaterNinja"
@ninja.save!
+7

WaterNinja#to_fireninja. Ruby , .

class WaterNinja < Ninja
  def to_fireninja
    FireNinja.new :name => name
  end
end
-1

All Articles