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

Dre*_*w H 4 ruby ruby-on-rails rails-postgresql postgresql-9.2 ruby-on-rails-4

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

rake aborted!
can't cast Array to json
Run Code Online (Sandbox Code Playgroud)

这是我的桌子

  class CreateTrips < ActiveRecord::Migration

          def change
            create_table :trips do |t|

              t.json :flights
              t.timestamps
            end
          end 
        end
Run Code Online (Sandbox Code Playgroud)

这是在我的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 
  }
)
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我不能这样做.如果我这样做

trip = Trip.create(
      {
        name: 'Flight',
        flights: { flights: flights.to_json }
      }
    )
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*vin 7

执行摘要:这是一个已知问题,并在此pull请求中解决,该请求在撰写本文时正在等待合并.

长版:

好吧,基于Array/Hash,我可以看到它为什么以及如何失败/成功.这是进行类型转换的Rails方法(来自quoting.rb),它显然不支持从Ruby转换Array为Postgres,json而它支持转换Hash.此外,我在此方法的开头添加了一些调试代码,发现使用flightsflights.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
Run Code Online (Sandbox Code Playgroud)

我继续向Array案例添加以下内容:

        when 'json' then PostgreSQLColumn.json_to_string(value)
Run Code Online (Sandbox Code Playgroud)

然后更改PostgreSQLColumn.json_to_string(在cast.rb中)以操作参数Array以及Hash类型,我能够让你的用例通过.

此时我还没有检查是否存在任何问题或请求

顺便说一句,我想你知道你可以通过使用text字段而不是字段来解决这个问题json.json我知道的唯一一件事就是在数据库级别进行验证.如果你认为这很重要,我会有兴趣知道为什么,因为我在网络应用程序中有一些带有json内容的文本字段我正在研究并且我想知道转换它们的好处,如果有的话.