Thursday, December 28, 2006

How to use Dynamic Object invocation in Rails for Models (String to Model conversion)

Requirement
-------------
You have String value of the model (model name) and you want to dynamically invoke methods on this model. This comes handy when you want to parse controller/action and do some neat nifty tricks.


Solution
-----------
model_name = "invoice"

model_name_capital = model_name.capitalize # => this creates "Invoice"

@object = Object.const_get(model_name).find(:all) # => This is equivalent to Invoice.find_all

No comments: