Reputation: 794
ruby : ruby 2.0.0p195 (2013-05-14 revision 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>
I am loading a user as shown above. The data type for in_games in postrges is integer[] I do not understand why I am receiving an error. (shown below)
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" = '---
Upvotes: 1
Views: 695
Reputation: 434955
Looks like you're abandoning your array approach but I'll leave some notes here for posterity.
Rails3 doesn't understand PostgreSQL's array types out of the box (AFAIK this is remedied in Rails4), you'll need to include the postgres_ext
or similar gem to make PostgreSQL arrays work with Rails3.
Without something to support arrays, ActiveRecord will try to YAMLize any input it doesn't understand, hence the odd looking string:
UPDATE "users" SET "in_games" = '---
^^^^
that ends up in your SQL. If you look at the whole SQL statement you should see a YAML version of your array.
As an aside, once you get array support working, this won't work the way you expect it to:
@user.in_games << @game.id
The postgres_ext
docs have this to say:
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.
If you say @user.in_games << @game.id
then you're modifying in_games
in-place and ActiveRecord won't notice that anything has changed, if you assign it a whole new array:
@user.in_games += [ @game.id ]
# equivalent to @user.in_games = @user.in_games + [ @game.id ]
then ActiveRecord will notice that in_games
has changed and everything (_changed?
methods, the SQL UPDATE, ...) should work as expected.
Upvotes: 1