Rails:将值序列化为逗号分隔而不是YAML
我正在寻找一种存储序列化值的方法,例如。 列中的ID。 在声称这不是最佳设计之前:该列用于关联记录的ID,但仅在显示记录时使用 – 因此不会对列上的选择进行查询,并且不会在此列上进行连接无论是。
在Rails中,我可以使用以下命令序列化列:
class Activity serialize :data end
这将列编码为YAML。 由于传统的缘故,因为我只存储只包含整数的一维数组,所以我发现它更适合将它存储为逗号分隔值。
我已经成功实现了这样的基本访问器:
def data=(ids) ids = ids.join(",") if ids.is_a?(Array) write_attribute(:data, ids) end def data (read_attribute(:data) || "").split(",") end
这很好用。 但是我想在这个属性中添加类似数组的方法:
activity = Activity.first activity.data << 42 ...
我该怎么办?
你可以使用这篇文章中解释的composition_offunction来完成它。 它应该是这样的:
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
虽然没有测试过。
您可以在rails 3.1中使用自定义编码器进行serialize
。
看看我对这个问题的回答 。 🙂
- Rails accepted_nested_attributes计数validation
- 我可以在ActiveRecord(或Mongoid)中为数据库连接和table_name配置线程安全的每个请求配置吗?
- 如何更改表单上的validation消息
- Rails:在模型上链接filter方法
- ActiveRecord语法,用于在使用连接时查找平均评级为x或更高的所有项目
- Rails:如何获取深度为2’has_many’级别的记录?
- 为什么Rails / ActiveRecord在ORDER中给出Postgres SyntaxError“非整数常量”?
- 如何使用rpec在Rails测试环境中加载seed.rb?
- Rails应用程序中的嵌套表单错误