Many times we came across a situation where we need to convert a string to respective class or model. So that we can call methods on it. Generally to handle this situation new rails developers use case statement like this,
case class_name_string when 'Account' object = Account.find(id) when 'Contact' object = Contact.find(id) when 'Opportunity' object = Opportunity.find(id) when 'Campaign' object = Campaign.find(id) when 'Model1' object = Model1.find(id) when 'Model2' object = Model2.find(id) : : : : when 'Modeln' object = Modeln.find(id]) end
This can be actually done pretty easily by using constantize in only one line
class_name_string.constantize.find(id)
No comments:
Post a Comment