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.
我正在寻找一种方法来存储eg的序列化值。id列。在声明这不是最优设计之前:该列用于相关记录的id,但仅在显示记录时使用——因此不会对列上的选择进行查询,也不会对该列进行连接。
In Rails I can serialize the column by using:
在Rails中,我可以使用:
class Activity
serialize :data
end
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-separated value.
这将列编码为YAML。为了传统的缘故,因为我只存储一个只包含整数的一维数组,所以我觉得它更适合作为逗号分隔的值存储。
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
This works pretty fine. However I'd like to add array-like methods to this attribute:
这工作很好。但是我想在这个属性中加入arraylike方法:
activity = Activity.first
activity.data << 42
...
How would I do this?
我该怎么做呢?
2 个解决方案
#1
3
You can do it with composed_of feature as explained in this post. It should be something like:
您可以使用本文所解释的composed_of特性来实现它。应该是这样的:
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.
没有测试过。
#2
1
You can use serialize
with a custom coder in rails 3.1.
您可以使用rails 3.1中的自定义编码器进行序列化。
See my answer to this question. :-)
请看我对这个问题的回答。:-)
#1
3
You can do it with composed_of feature as explained in this post. It should be something like:
您可以使用本文所解释的composed_of特性来实现它。应该是这样的:
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.
没有测试过。
#2
1
You can use serialize
with a custom coder in rails 3.1.
您可以使用rails 3.1中的自定义编码器进行序列化。
See my answer to this question. :-)
请看我对这个问题的回答。:-)