lundi 3 juillet 2017

Model serilize hash turned from hash to string when saving object

ruby 2.3.3, rails 3.2.22.5

Hi. I'm using a serialized :logs, Hash in a User model, when saving the logs hash- afterwards it's being retrieved as string instead of Hash.

How it happen:

  1. assign value to logs hash
  2. save user object
  3. now logs hash is a string..

So for user when assigning value to logs hash: user.logs[2] = 4, then saving

class User < ActiveRecord::Base
  serialize :logs, Hash # in database it's a text type
end

An example in the rails console:

# rails console
test_user_id = 3
user = User.find(test_user_id)
user.logs = {}
user.save

user.logs # => {} # great
User.find(test_user_id).logs # => {} # great
# now trying to add value and save:

# 1. assign value to logs hash
user.logs[Time.now] = {:field_id=>6} # => {:field_id=>6}
# 2. save user object:
user.save
# 3. now logs hash is a string..
user.logs
#=> "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n" 
# why it turned to string ?!?!

User.find(test_user_id).logs # same here:
# => "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"

Any ideas?

Aucun commentaire:

Enregistrer un commentaire