ruby-on-rails - 转换为自定义类型的 PostgreSQL 数组

标签 ruby-on-rails postgresql

在 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/

相关文章:

ruby-on-rails - Rails 4 + 设计单独的用户 CRUD

ruby-on-rails - Rails 清除 heroku 上的缓存

javascript - Rails 在提交之前验证 form_for

sql - 表单中的必填字段现在必须设为可选,新字段成为必填字段,同时与原始字段具有可选关系

postgresql - 废弃的 Postgres 模板 1

sql - 如何从 postgreSQL INDEX 中选择数据?

postgresql - 查找我的 Postgres 文本搜索词典

ruby-on-rails - Rails 将多列查询转换为 strftime ("%H") ... NoMethodError : undefined method `strftime'

ruby-on-rails - 请按语法排序 Mongoid Scope

postgresql - 在 PL/pgSQL 函数中使用变量