我正在尝试使用StoreModel gem通过类来备份我的jsonb数据。尝试定义数组属性时,出现ArgumentError(未知关键字:array)。例如:
class A
include StoreModel::Model
attribute :my_array, :integer, array:true, default:Array.new
end
将其键入irb将产生错误。
经进一步检查,它似乎与StoreModel gem无关。
class A
include ActiveModel::Model
include ActiveModel::Attributes
attribute :my_array, :integer, array:true, default:Array.new
end
将产生相同的结果。根据Attributes API,该类不需要由数据库表支持。但是,当我尝试示例时:
class MyModel < ActiveRecord::Base
attribute :my_string, :string
attribute :my_int_array, :integer, array: true
attribute :my_float_range, :float, range: true
end
model = MyModel.new(
my_string: "string",
my_int_array: ["1", "2", "3"],
my_float_range: "[1,3.5]",
)
在IRB中,它尝试执行SQL查询,因此我得到:
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: relation "my_models" does not exist)
LINE 8: WHERE a.attrelid = '"my_models"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
c.collname, col_description(a.attrelid, a.attnum) AS comment
FROM pg_attribute a
LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
WHERE a.attrelid = '"my_models"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
答案 0 :(得分:2)
宝石的作者在这里:)问题here中正在进行讨论–我稍后将实现对数组的真正支持,但是有一种解决方法:
class ArrayOfStringsType < ActiveRecord::Type::Value
def type
:array_of_strings
end
end
class ArrayOfIntegersType < ActiveRecord::Type::Value
def type
:array_of_integers
end
def cast(values)
return if values.blank?
values.map(&:to_i)
end
end
ActiveModel::Type.register(:array_of_strings, ArrayOfStringsType)
ActiveModel::Type.register(:array_of_integers, ArrayOfIntegersType)
class Configuration
include StoreModel::Model
attribute :colors, :array_of_strings, default: -> { [] }
attribute :prices, :array_of_integers, default: -> { [] }
end