在一个Rails(5.2)应用程序中,我有一个名为
为了实现这一点,我正在尝试使用Rails 5提供的属性API。
Project
的模型,其中定义了一个作为Postgresql数组的tags
属性。 create_table :projects do |t|
...
t.text :tags, array: true, default: []
...
end
我希望将标签作为字符串处理的方式改成将其转换为 Tag
对象。
class Tag
...
attr_reader :name
def initialize(name)
@name = name
end
...
end
为了实现这一点,我正在尝试使用Rails 5提供的属性API。
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
这种工作会创建Tag
对象,但第一个和最后一个名称中有括号。
Project.create(tags: ['one', 'two', 'three'])
Project.first.tags.map(&:name) #=> ['{one', 'two', 'three}']
有没有比手动从TagType
中删除括号以获得正确的Tag
更好的方法?
试图在Rails代码中查找解析数组值的位置,但迄今为止没有成功。
connection_adapters/postgresql/oid/array.rb
开始,解码数组比简单的String#split
调用要复杂一些,因为你需要处理像'{"a b", c, d}'
这样的情况。 - undefined