ruby : ruby 2.0.0p195(2013-05-14 修订版 40734)[x86_64-darwin12.3.0]
@user = User.find(1)
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
=> #<User id: 1, first_name: "d", last_name: "g", crypted_password: "$2a$10$h4Bil49Pw.bxf0jXvw4mEeYzKh2tgL9kUx/CtBeTg2HB...", salt: "3r3xXr3oqHGP5MpzdxAE", in_games: nil>
我正在加载一个用户,如上所示。 postrges中in_games的数据类型是integer[] 我不明白为什么会收到错误消息。 (如下图)
if @user.in_games.nil?
array = []
@user.in_games = array.push(@game.id)
else
@user.in_games << @game.id
end
@user.save
ActiveRecord::StatementInvalid: PGError: ERROR: array value must start with "{" or dimension information
LINE 1: UPDATE "users" SET "in_games" = '---
^
: UPDATE "users" SET "in_games" = '---
最佳答案
看起来您正在放弃数组方法,但我会在这里为后代留下一些注释。
Rails3 不理解 PostgreSQL 开箱即用的数组类型(据我所知,这在 Rails4 中得到了补救),您需要包含 postgres_ext
或类似的 gem 使 PostgreSQL 数组与 Rails3 一起工作。
如果没有支持数组的东西,ActiveRecord 将尝试 YAMLize 它不理解的任何输入,因此看起来很奇怪的字符串:
UPDATE "users" SET "in_games" = '---
^^^^
最终出现在您的 SQL 中。如果查看整个 SQL 语句,您应该会看到数组的 YAML 版本。
顺便说一句,一旦你获得了数组支持,这将不会像你期望的那样工作:
@user.in_games << @game.id
postgres_ext
文档是这样说的:
The following will modify the default value of the names attribute.
a = Item.new a.names << 'foo' b = Item.new puts b.names # => ['foo']
The supported way of modifying
a.names
:a = Item.new a.names += ['foo'] b = Item.new puts b.names # => []
As a result, in place operators are discouraged and will not be supported in postgres_ext at this time.
如果你说 @user.in_games << @game.id
那么你正在修改 in_games
如果您为它分配一个全新的数组,就地和 ActiveRecord 不会注意到任何更改:
@user.in_games += [ @game.id ]
# equivalent to @user.in_games = @user.in_games + [ @game.id ]
然后 ActiveRecord 会注意到 in_games
已经改变,一切(_changed?
方法、SQL 更新,...)应该按预期工作。
关于ruby-on-rails - ruby 中的 Postgres 数据类型整数 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16971806/