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.
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>, ...]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With