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?
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?
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
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)
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