In a Rails (5.2) app I have the Project model with a tags attribute defined as a Postgresql array.
create_table :projects do |t|
...
t.text :tags, array: true, default: []
...
end
Instead of handling tags as strings I'd like to cast them to Tags objects
class Tag
...
attr_reader :name
def initialize(name)
@name = name
end
...
end
To achieve so I'm trying to use the attributes API that comes with Rails 5.
class Project < ApplicationRecord
attribute :tags, TagType.new, array: true
...
end
class TagType < ActiveRecord::Type::Value
def cast(names)
names.split(',').map { |name| Tag.new(name) }
end
end
This kind of work, it creates Tags object but the first and last have brackets in the name.
Project.create(tags: ['one', 'two', 'three'])
Project.first.tags.map(&:name) #=> ['{one', 'two', 'three}']
Is there a better way than manually removing the brackets from names in TagType to get proper Tags?
Trying to find in Rails code where the array value is parsed but no luck so far.
connection_adapters/postgresql/oid/array.rbin the ActiveRecord source, decoding arrays is a little more complicated than a simpleString#splitcall as you have to deal with things like'{"a b", c, d}'and the like.