views:

189

answers:

4
class User < ActiveRecord::Base   
end  

class Consumer < User 
end  

class Merchant < User 
end   

u = User.find(id)

How do I type cast the variable u to the type Consumer?

A: 

You need a column called 'type' and rails will do the rest. For example:

id = Consumer.create!(...).id

# later on

User.find(id).is_a? Consumer  # ==> true
Marc-André Lafortune
A: 

I found the answer to this. The ActiveRecord::Base class has a method for this purpose:

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

The code will be

u = User.find(id)
u = u.becomes(u.type.constantize)
KandadaBoggu
becomes can be used to "fake" that a record is of a given type. As in the doc, this might be useful to use for a subclass.In your "solution", becomes does nothing useful since u.class == u.type.constantize
Marc-André Lafortune
Marc, You are right, but my confusion was due to a STI bug. I have explained it in my 2nd answer.
KandadaBoggu
A: 

Due to a bug in STI, the ActiveRecord finder was returning a base class instance(User) instead of subclass instance(Consumer). I thought this is the default behavior and hence wanted to cast the base class instance(User) to the sub class instance(Consumer). My previous solution became redundant after addressing the bug. i.e.

u = User.find(id) # returns an instance of Consumer class
KandadaBoggu
A: 

You can always get a Consumer as such:

u = Consumer.find(id)
lillq