【发布时间】:2013-06-04 11:31:01
【问题描述】:
所以我很感兴趣是否有办法将字符串转换为活动记录类。
示例:我有一个继承自 ActiveRecord::Base 的 User 类。
有什么办法可以将字符串"User" 转换为User 类,这样我就可以使用ActiveRecord 方法,例如find、where 等。
【问题讨论】:
标签: ruby ruby-on-rails-3 activerecord
所以我很感兴趣是否有办法将字符串转换为活动记录类。
示例:我有一个继承自 ActiveRecord::Base 的 User 类。
有什么办法可以将字符串"User" 转换为User 类,这样我就可以使用ActiveRecord 方法,例如find、where 等。
【问题讨论】:
标签: ruby ruby-on-rails-3 activerecord
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])
没有任何安全问题。
【讨论】: