[英]Can i store a ruby hash in a mysql database column
I want to insert hashes like below into a mysql column, 我想将以下散列插入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] }
I tried, its throwing the following error, 我尝试过,它引发以下错误,
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...
Any help? 有什么帮助吗?
EDIT: 编辑:
Forget active record and serialization. 忘记活动记录和序列化。 I want to do it in a raw sql.
我想在原始SQL中执行此操作。
您需要对哈希中的单引号进行转义
If you want to store Hash inside column in MySQL (or any other database supported by AR*) you have to: 如果要将哈希存储在MySQL(或AR *支持的任何其他数据库)的列中,则必须:
1) define column as text 1)将列定义为文本
add_column :users, :the_whatever, :text
2) define serialization of column so that ActiveRecord knows what to do with you data. 2)定义列的序列化,以便ActiveRecord知道如何处理您的数据。 You do this by setting serialize option to model.
您可以通过将serialize选项设置为model来做到这一点。
serialize :the_whatever, Hash
* Some databases (like PostgreSQL) also provide some other types more suited for storing Hashes. *一些数据库(如PostgreSQL)还提供了其他一些更适合存储哈希的类型。 See Railscasts Hstore .
请参阅Railscasts Hstore 。
如果您愿意切换数据库:PostreSQL为此提供了hstore 。
Your sql column must be of type text
. 您的sql列必须为
text
类型。 You might need to serialize your hash first too. 您可能还需要先序列化哈希。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.