Rails 4.1 Postgres String Arrays: Can't Save After Modifying -
weirdness:
i'm working in rails 4.1 postgres backend. 1 of models has array fields, i'm hoping handled 'pg' gem (0.17.1). migration file , resulting schema can found below.
the field in question string array. below, i've posted migration, resulting schema, , code doesn't seem working (along output when code run in rails console).
i don't have in user model references field.
migration:
add_column :users, :test, :string, :array => true, default: '{}'
schema:
t.string "test", default: [], array: true
here steps i'm using to reproduce in rails console (assuming basic user model has been created hold field):
u = user.first() u.test.push('testvalue') u # => #<user id: 1, name: "dave", passhash: nil, email: nil, created_at: "2014-10-04 10:12:29", updated_at: "2014-10-04 10:12:29", provider: "identity", uid: "1", oauth_token: nil, oauth_expires_at: nil, test: ["testvalue"]> u.save user.find(1).test # => []
so user record seems initialized -- has empty array set field -- , can array operations on it. somehow can't modifications stick.
fyi, able modify , save other fields using same procedure; it's just arrays behaving this.
any ideas?
edit:
u.test.push('newitem')returns new array expect. no sign of going wrong, or error validates_uniqueness_of -- see firing in console? first comment, i've tested using 'update':
u.update(test: [(u.test << 'testvalue')].flatten)
gives me behavior want, seems clumsy. there need alter in model? i'm not sure how i'm doing makes validates_uniqueness_of fire (it's not set in model).
there (at to the lowest degree used be) problem using ruby array operators push
or <<
on activerecord fields. not marked dirty , not updated in database on save
. seek this:
u = user.first() u.test_will_change! u.test.push('testvalue') u.save user.find(1).test
attribute_will_change!
marks attribute dirty, making sure serialized , saved database on save
.
ruby-on-rails arrays pg
No comments:
Post a Comment