无法在postgresql(rails)中的json字段中存储数组,无法将数组转换为json
这是我运行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数组。 不是我想要的行为。
Exec摘要:这是一个已知问题,并在此pull请求中解决,该请求在撰写本文时正在等待合并。
长版:
好吧,基于Array / Hash,我可以看到它为什么以及如何失败/成功。 这是进行类型转换的Rails方法(来自quoting.rb),它显然不支持从Ruby Array
为Postgres json
而它支持从Hash
。 此外,我在此方法的开头添加了一些调试代码,发现使用flights.to_json
或flights.to_json
作为值无关紧要,因为后者为了此转换而转换为前者。 我要做更多的挖掘,因为我没有问题使用psql将flights.to_json
的值插入到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
案例中:
when 'json' then PostgreSQLColumn.json_to_string(value)
然后更改PostgreSQLColumn.json_to_string
(在cast.rb中)来操作Array
和Hash
类型的参数,我能够让你的用例通过。
此时我还没有检查是否存在任何问题或拉取请求
顺便说一句,我假设你知道你可以通过使用text
字段而不是json
字段来解决这个问题。 json
为您提供的唯一一件事我知道是否在数据库级别进行validation。 如果你认为这很重要,我会有兴趣知道为什么,因为我在我正在研究的网络应用程序中有一些带有json内容的文本字段,我想知道转换它们的好处,如果有的话。