views:

62

answers:

3

Hi, I'm currently using activerecord STI and trying to cast an object type from A to B (same parent). Is there a standard way of achieving that?

A: 

Create a new instance of B to setting the values for attributes it shares with A.

Something like:

class C < ActiveRecord::Base
end

class A < C
end

class B < C
end

@a = A.new(...)
@b = B.new(@a.attr1, @a.attr2, ..., @a.attrN)
bjg
This is not casting... is it?
Webbisshh
@Webbisshh No, it's not. This is an approximation for the particular problem posed in the question.
bjg
+3  A: 

You shouldn't need to cast since Ruby isn't a strictly-typed language. What are you trying to accomplish?

Say you have a class Dad, and child classes Son and Daughter.

You could just have a variable @dad and store in it either a Son or Daughter object, and just treat it as if it were a Dad. As long as they respond to the same methods, it makes no difference. This is a concept called "duck typing".

Karl
+2  A: 

#becomes is what you are looking for:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001849

Omar Qureshi