Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string object to active record class

So I am interested if there is a way to convert string to active record class.

Example: I have a User class which has inherited from ActiveRecord::Base. Is there any way I can convert string "User" to User class so I can use ActiveRecord methods such as find, where, etc.

like image 441
Antonio Novoselnik Avatar asked Jun 04 '13 11:06

Antonio Novoselnik


2 Answers

String#constantize returns the value for the constant with the string's name. For "User" this is your User class:

"User".constantize
# => User(id: integer, ...)

You can assign this to a variable and call ActiveRecord methods:

model = "User".constantize
model.all
# => [#<User id:1>, #<User id:2>, ...]
like image 155
Stefan Avatar answered Sep 24 '22 03:09

Stefan


You just write in you code

str="User"
 class_name=str.constantize

and you will get like this format data

User(id: integer, login: string, name: string, email: string, user_rank: integer

User as class name

Second Method is class_name= Object.const_get(str)

like image 34
Ravendra Kumar Avatar answered Sep 23 '22 03:09

Ravendra Kumar