【问题标题】:Can i store a ruby hash in a mysql database column我可以在 mysql 数据库列中存储 ruby​​ 哈希吗
【发布时间】:2013-03-12 03:30:10
【问题描述】:

我想将如下所示的哈希值插入到 mysql 列中,

{:sub => ["at","div.product-info"],
     1 => [["at","span#hs18Price"]],
     :avail => ["at","strong.out_stock"],
     :soffer =>  ["at","div.freebie"], 
     :stime =>["search","div[@class='costs']//span[@class='days']"],
     :scost => [300,30] }

我试过了,它抛出以下错误,

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'costs...

有什么帮助吗?

编辑:

忘记活动记录和序列化。我想用原始的 sql 来做。

【问题讨论】:

    标签: mysql ruby hash


    【解决方案1】:

    您需要转义散列中的单引号

    【讨论】:

      【解决方案2】:

      如果您想在 MySQL(或 AR* 支持的任何其他数据库)的列内存储 Hash,您必须:

      1) 将列定义为文本

      add_column :users, :the_whatever, :text
      

      2) 定义列的序列化,以便 ActiveRecord 知道如何处理您的数据。您可以通过将序列化选项设置为模型来做到这一点。

      serialize :the_whatever, Hash
      

      * 一些数据库(如 PostgreSQL)还提供了一些更适合存储哈希的其他类型。见Railscasts Hstore

      【讨论】:

        【解决方案3】:

        如果您愿意切换数据库:PostreSQL 有 hstore 用于此。

        【讨论】:

        • Postgres 9.2 也有 JSON 数据类型。
        【解决方案4】:

        您的 sql 列必须是 text 类型。您可能还需要先序列化您的哈希。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-16
          • 2021-10-12
          • 2019-03-17
          相关资源
          最近更新 更多