如何在数据库中正确保存数组?
How to save array in database correctly?
我想在数据库中添加数组。我使用ruby, sequel and postgresql,但问题是真正的方式,而不是程序实现。
我看到 3 条路径:
- 使用特殊 adapters. It help to save array like
[1,2,3,4]
in db after some changes: in database it will look like "{1,2,3,4}"
。但是在它之后我不知道如何将这个条目转换回 [1,2,3,4]
而不是废话。
- 将数组转换为 json 并将其保存到数据库中。像
[1,2,3,4]
这样的数组看起来像 "[1,2,3,4]"
。我可以通过 JSON.parse
. 轻松转换回来
- 通过Marshal转换数组并保存。数组
[1,2,3,4]
看起来像 "\x04\b[\ti\x06i\ai\bi\t"
,但它有风险,因为数据可以在 ruby 更新后更改(或者我错了)
谁能说说真道?
恕我直言,干净的方法是额外的 table。理想情况下,数据库中的每一行都代表一个观察值,并且具有数组或 json 列很可能与此相矛盾。我建议将额外的 table 视为良好的设计,而不是矫枉过正。
利用ActiveRecord
提供的serialize
class User < ApplicationRecord
serialize :preferences, Array
end
#In migration Add a string field
class AddSerializePreferencesToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :preferences, :string
end
end
#In rails console.
u = User.first
u.preferences # => []
u.preferences << 'keep coding'
u.preferences # => ['keep coding']
u.save
u.reload.preferences # ['keep coding']
希望对您有所帮助
Sequel 原生支持 Postgres 数组列,假设您不需要进一步规范化您的架构。
How do I define an ARRAY column in a Sequel Postgresql migration?
http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_array_rb.html
我想在数据库中添加数组。我使用ruby, sequel and postgresql,但问题是真正的方式,而不是程序实现。 我看到 3 条路径:
- 使用特殊 adapters. It help to save array like
[1,2,3,4]
in db after some changes: in database it will look like"{1,2,3,4}"
。但是在它之后我不知道如何将这个条目转换回[1,2,3,4]
而不是废话。 - 将数组转换为 json 并将其保存到数据库中。像
[1,2,3,4]
这样的数组看起来像"[1,2,3,4]"
。我可以通过JSON.parse
. 轻松转换回来
- 通过Marshal转换数组并保存。数组
[1,2,3,4]
看起来像"\x04\b[\ti\x06i\ai\bi\t"
,但它有风险,因为数据可以在 ruby 更新后更改(或者我错了) 谁能说说真道?
恕我直言,干净的方法是额外的 table。理想情况下,数据库中的每一行都代表一个观察值,并且具有数组或 json 列很可能与此相矛盾。我建议将额外的 table 视为良好的设计,而不是矫枉过正。
利用ActiveRecord
提供的serializeclass User < ApplicationRecord
serialize :preferences, Array
end
#In migration Add a string field
class AddSerializePreferencesToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :preferences, :string
end
end
#In rails console.
u = User.first
u.preferences # => []
u.preferences << 'keep coding'
u.preferences # => ['keep coding']
u.save
u.reload.preferences # ['keep coding']
希望对您有所帮助
Sequel 原生支持 Postgres 数组列,假设您不需要进一步规范化您的架构。
How do I define an ARRAY column in a Sequel Postgresql migration?
http://sequel.jeremyevans.net/rdoc-plugins/files/lib/sequel/extensions/pg_array_rb.html