问题描述
我想这样保存数据:
User.create(name:"Guy", properties:{url:["url1","url2","url3"], street_address:"asdf"})
我可以在 Rails 4 中这样做吗?到目前为止,我已经尝试过迁移:add_column :users, :properties, :hstore, array: true
Can I do so in Rails 4? So far, I have tried migration:add_column :users, :properties, :hstore, array: true
但是当我将数组保存在 hstore 中时,它返回错误:
But when I save the array in hstore, it returns error:
PG::InvalidTextRepresentation: ERROR: 数组值必须以{"或维度信息开头
推荐答案
hstore
用于简单的键/值存储,其中键和值都是简单的非结构化字符串.来自精美手册:
hstore
is intended for simple key/value storage, where both the keys and values are simple unstructured strings. From the fine manual:
F.16.hstore
该模块实现了 store
数据类型,用于在单个 PostgreSQL 值中存储键/值对集.[...] 键和值只是文本字符串.
This module implements the store
data type for storing sets of key/value pairs within a single PostgreSQL value. [...] Keys and values are simply text strings.
注意最后一句:hstore
中的键和值都是字符串.这意味着你不能把数组放在 hstore
值中,而没有一些处理来将数组转换为字符串和从字符串转换,而且你真的不想搞乱那种事情.
Note the last sentence: keys and values in hstore
are strings. That means that you can't put an array in an hstore
value without some handholding to convert the array to and from a string and you really don't want to be messing around with that sort of thing.
但是,有一个 JSON 数据类型可用:
8.14.JSON 类型
json
数据类型可用于存储 JSON(JavaScript 对象表示法)数据,如 RFC 4627 中所述.
The json
data type can be used to store JSON (JavaScript Object Notation) data, as specified in RFC 4627.
和 JSON 可以轻松处理嵌入的数组和对象.尝试改用 JSON:
and JSON can easily handle embedded arrays and objects. Try using JSON instead:
add_column :users, :properties, :json
不过,您必须先删除旧的 hstore
列.
You'll have to remove the old hstore
column first though.
此外,您不希望 array: true
在您的 hstore
列中,因为您没有存储 hstore
的数组,你只想要其中之一.
Also, you didn't want array: true
on your hstore
column as you weren't storing an array of hstore
s, you just wanted one of them.
这篇关于我可以使用 Rails 在 hstore 中存储数组吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!