无法在 postgresql (rails) 的 json 字段中存储数组无法将数组转换为 json

2024-01-29

这是我运行 db:migrate 时遇到的错误

rake aborted!
can't cast Array to json

这是我的桌子

  class CreateTrips < ActiveRecord::Migration

          def change
            create_table :trips do |t|

              t.json :flights
              t.timestamps
            end
          end 
        end

这是在我的 seeds.rb 文件中

flights = [{
    depart_time_hour: 600,
    arrive_time_hour: 700,

    passengers: [
        {
            user_id: 1,
            request: true    
        }
    ]
}]

trip = Trip.create(
  {
    name: 'Flight',

    flights: flights.to_json 
  }
)

由于某种原因我不能这样做。如果我这样做。

trip = Trip.create(
      {
        name: 'Flight',
        flights: { flights: flights.to_json }
      }
    )

有用。但我不想要这个,因为现在我必须使用 trip.flights.flights 访问 json 数组。这不是我想要的行为。


执行摘要:这是已知的issue https://github.com/rails/rails/issues/11169并在此解决拉取请求 https://github.com/rails/rails/commit/9b66187622453679497ad2fed4f333e2fca32150,在撰写本文时正在等待合并。

长版:

好吧,我可以根据数组/哈希了解它失败/成功的原因和方式。这是进行类型转换的 Rails 方法(来自 quoting.rb),它显然不支持从 Ruby 进行转换Array到 Postgresjson虽然它确实支持从Hash。另外,我在这个方法的开头放了一些调试代码,发现使用也没关系flights or flights.to_json作为值,因为出于此转换的目的,后者被转换为前者。我将进行更多挖掘,因为插入值没有问题flights.to_json使用 psql 转换为 json 列。

    def type_cast(value, column, array_member = false)
      return super(value, column) unless column

      case value
      when Range
        return super(value, column) unless /range$/ =~ column.sql_type
        PostgreSQLColumn.range_to_string(value)
      when NilClass
        if column.array && array_member
          'NULL'
        elsif column.array
          value
        else
          super(value, column)
        end
      when Array
        case column.sql_type
        when 'point' then PostgreSQLColumn.point_to_string(value)
        else
          return super(value, column) unless column.array
          PostgreSQLColumn.array_to_string(value, column, self)
        end
      when String
        return super(value, column) unless 'bytea' == column.sql_type
        { :value => value, :format => 1 }
      when Hash
        case column.sql_type
        when 'hstore' then PostgreSQLColumn.hstore_to_string(value)
        when 'json' then PostgreSQLColumn.json_to_string(value)
        else super(value, column)
        end
      when IPAddr
        return super(value, column) unless ['inet','cidr'].include? column.sql_type
        PostgreSQLColumn.cidr_to_string(value)
      else
        super(value, column)
      end
    end

我继续将以下行添加到Array case:

        when 'json' then PostgreSQLColumn.json_to_string(value)

然后改变了PostgreSQLColumn.json_to_string(在cast.rb中)对以下参数进行操作ArrayHash输入,我能够让你的用例通过。

目前我还没有检查是否存在任何问题或拉取请求

顺便说一句,我假设你知道你可以通过使用来解决这个问题text字段而不是json场地。唯一的一点就是json为您提供我知道是否在数据库级别进行验证。如果您认为这很重要,我有兴趣知道为什么,因为我正在开发的 Web 应用程序中有一些带有 json 内容的文本字段,我想知道转换它们的好处(如果有) 。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 postgresql (rails) 的 json 字段中存储数组无法将数组转换为 json 的相关文章

随机推荐