所以我感兴趣的是有没有办法将字符串转换为活动记录类。
示例:我有一个继承自User
的ActiveRecord::Base
类。有什么方法我可以将字符串"User"
转换为User
类,所以我可以使用ActiveRecord
方法,如find
,where
等。
String#constantize
使用字符串的名称返回常量的值。对于"User"
,这是你的User
类:
"User".constantize
# => User(id: integer, ...)
您可以将其分配给变量并调用ActiveRecord方法:
model = "User".constantize
model.all
# => [#<User id:1>, #<User id:2>, ...]
你只需在代码中写下来
str="User"
class_name=str.constantize
你会得到这样的格式数据
User(id: integer, login: string, name: string, email: string, user_rank: integer
用户作为班级名称
第二种方法是class_name = Object.const_get(str)
更安全的方式:
"string".classify.constantize.find(....)
而是在您的字符串类中定义一个方法
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
然后用
"user".constantize_with_care([User])
现在你可以做这样的事了
params[:name].constantize_with_care([User])
没有任何安全问题。