将字符串对象转换为活动记录类

时间:2013-06-04 11:31:02

标签: ruby ruby-on-rails-3 activerecord

所以我感兴趣的是有没有办法将字符串转换为活动记录类。

示例:我有一个继承自User的{​​{1}}类。 有什么方法可以将字符串ActiveRecord::Base转换为"User"类,以便我可以使用UserActiveRecordfind方法。

4 个答案:

答案 0 :(得分:11)

String#constantize返回带有字符串名称的常量的值。对于"User",这是您的User类:

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

您可以将其分配给变量并调用ActiveRecord方法:

model = "User".constantize
model.all
# => [#<User id:1>, #<User id:2>, ...]

答案 1 :(得分:3)

你只需写下代码

str="User"
 class_name=str.constantize

你会得到的  喜欢这种格式数据

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

用户作为班级名称

第二种方法 class_name = Object.const_get(str)

答案 2 :(得分:1)

更安全的方式:

"string".classify.constantize.find(....)

答案 3 :(得分:1)

而是在字符串类中定义方法

     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])

没有任何安全问题。