【问题标题】:Convert string object to active record class将字符串对象转换为活动记录类
【发布时间】:2013-06-04 11:31:01
【问题描述】:

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

示例:我有一个继承自 ActiveRecord::BaseUser 类。 有什么办法可以将字符串"User" 转换为User 类,这样我就可以使用ActiveRecord 方法,例如findwhere 等。

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 严格来说,它返回绑定到给定常量名称的任何对象,而不仅仅是模块/类。
    • 谢谢,这正是我想要的。
    【解决方案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)

    【讨论】:

      【解决方案3】:

      更安全的方式:

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

      【讨论】:

        【解决方案4】:

        而是在你的字符串类中定义一个方法

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

        没有任何安全问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-07
          • 2011-09-30
          • 1970-01-01
          • 2011-07-21
          • 1970-01-01
          • 2018-09-12
          相关资源
          最近更新 更多