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

Posted by Rajesh Shetty on December 29, 2006

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

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments