扶手:序列化值作为逗号分隔的,而不是YAML [英] Rails: Serialize value as comma-seperated and not as YAML
问题描述
我正在寻找一种方式来存储,例如一个序列化值。标识中的一列。在之前声称这是不是最佳设计:列用于相关记录的ID,但显示的记录时,将只使用 - 与选择的列,因此没有查询制成,没有联接将在此列作无论是。
I'm looking for a way to store a serialized value of eg. IDs in a column. In before claims that this is not an optimal design: the column is used for IDs of associated records, but will only be used when displaying the record - so no queries are made with selection on the column and no joins will be made on this column either.
在我的Rails可以通过序列化列:
In Rails I can serialize the column by using:
class Activity
serialize :data
end
这EN codeS的列YAML。对于旧酒,因为我只存储一个只包含整数一维数组,我觉得它更适合将其保存为一个逗号分隔值。
This encodes the column as YAML. For legacy sake and since I'm only storing one dimensional arrays containing only integers, I find it more suitable to store it as a comma-seperated value.
我已经成功地实施了基本的访问是这样的:
I've successfully implemented basic accessors like this:
def data=(ids)
ids = ids.join(",") if ids.is_a?(Array)
write_attribute(:data, ids)
end
def data
(read_attribute(:data) || "").split(",")
end
本作品pretty的罚款。不过,我想补充类似数组的方法将这些属性:
This works pretty fine. However I'd like to add array-like methods to this attribute:
activity = Activity.first
activity.data << 42
...
我将如何做到这一点?
How would I do this?
谢谢!
推荐答案
您可以使用的 composed_of 功能的解释在这个岗位。 它应该是这样的:
You can do it with composed_of feature as explained in this post. It should be something like:
composed_of :data, :class_name => 'Array', :mapping => %w(data to_csv),
:constructor => Proc.new {|column| column.to_csv},
:converter => Proc.new {|column| column.to_csv}
after_validation do |u|
u.data = u.data if u.data.dirty? # Force to serialize
end
还没有,虽然进行了测试。
Haven't tested it though.
这篇关于扶手:序列化值作为逗号分隔的,而不是YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!