Rails: Serialize the value as comma separated, not YAML

I am looking for a way to store a serialized value, for example. The identifiers in the column. Before claiming that this is not an optimal design: the column is used for identifiers of related records, but will only be used when displaying a record, so queries will not be made with a choice in the column, and there will be no joins in either column either.

In Rails, I can serialize a column using:

class Activity
   serialize :data
end

This encodes the column as YAML. For inheritance, and since I only store one-dimensional arrays containing only integers, I find it more convenient to store it as a comma-separated value.

I have successfully implemented the main accessors, for example:

def data=(ids)
    ids = ids.join(",") if ids.is_a?(Array)
    write_attribute(:data, ids)
end

def data
    (read_attribute(:data) || "").split(",")
end

It works very well. However, I would like to add such array attributes to this attribute:

activity = Activity.first
activity.data << 42
...

?

+3
2

created_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

, .

+3

serialize 3.1.

. .: -)

+1

Source: https://habr.com/ru/post/1761498/


All Articles