Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting base class models in Single Table Inheritence(STI) scenario

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?

like image 357
Harish Shetty Avatar asked Dec 02 '22 06:12

Harish Shetty


1 Answers

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)
like image 80
Harish Shetty Avatar answered Jan 11 '23 01:01

Harish Shetty