Yusuke Fujita
Yusuke Fujita

Reputation: 101

How to get a model using a variable in Ruby on rails

Is it possible to get the data by assigning the Model name to a variable like this?

I would like to retrieve data using the dynamic model name passed in as a parameter.

#Test is the model name
model_name = "Test"
model_name.all

Upvotes: 0

Views: 215

Answers (1)

Bhushan Kalode
Bhushan Kalode

Reputation: 54

You can used constantize over string to retrieve data from model.

Let say "User" is my model name then I can retrive all users as below.

"User".constantize.all

This will return all user to me.

In your case

"Test".constantize.all

If you are not sure input string will not be camel case then you can use as below.

"Test".classify.constantize.all

For reference -

constantize

classify

Upvotes: 3

Related Questions