Convert string object to active record class

Therefore, I am wondering if there is a way to convert a string to the active recording class.

Example: I have a User class inherited from ActiveRecord::Base . Is there a way to convert the string "User" to User , so I can use ActiveRecord methods like find , where , etc.

+7
source share
4 answers

String#constantize returns a constant with the specified 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>, ...] 
+10
source

You just write in your code

 str="User" class_name=str.constantize 

and you will get both data of this format

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

User as class name

Second method class_name = Object.const_get (str)

+3
source

safe way:

 "string".classify.constantize.find(....) 
+1
source

Instead, define a method in your string class

  def constantize_with_care(list_of_klasses=[]) list_of_klasses.each do |klass| return self.constantize if self == klass.to_s end raise "Not allowed to constantize #{self}!" end 

Then use

  "user".constantize_with_care([User]) 

and now you can do something like this

 params[:name].constantize_with_care([User]) 

Without any security issues.

+1
source

All Articles