在 Rails (5.2) 应用程序中,我有 Project
模型,其中 tags
属性定义为 Postgresql 数组。
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
中手动删除 names
中的括号以获得正确的 Tag
更好的方法?
试图在 Rails 代码中找到数组值被解析的位置,但到目前为止没有运气。
最佳答案
这是我最终得到的代码
class TagType < ActiveRecord::Type::Value
include ActiveModel::Type::Helpers::Mutable
def cast(name)
Tag.new(name)
end
def deserialize(names)
PG::TextDecoder::Array.new.decode(names).map { |name| cast(name) }
end
def serialize(tags)
PG::TextEncoder::Array.new.encode(tags.map(&:name))
end
end
希望这对您有所帮助。
关于ruby-on-rails - 转换为自定义类型的 PostgreSQL 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711754/