问题
I am upgrading my application to Rails 4.2.4 from Rails 3.2.8 . I have a 'extras' attribute for a table 'editorials' which is serialized
store :extras, accessors: [:attr1, :attr2, :attr3], coder: JSON
#The way it is stored in **Rails 3** is
---
:attr1: value
:attr2: value
:attr3: value
#The way it is stored in **Rails 4** is
{"attr1":"value", "attr2":"value", "attr3":"value"}
The problem when i fetch old records created when my app is in rails 3, it is throwing me error
JSON::ParserError: 795: unexpected token at '---
But when i create new records, it is working normally. Have not got any clue yet, how it get it working in Rails 4
回答1:
I found the solution finally. The "store accessor" (mentioned in the question) implementation is changed in activerecord 4.2.4. Earlier(active record 3.2.8 ) the data is stored in database is in YAML format, and it was working with "coder: JSON", which is not case in activerecord 4.2.4
Here is the code link 4.2.4 https://github.com/rails/rails/blob/master/activerecord/lib/active_record/store.rb#L85
Here is the code link 3.2 https://github.com/rails/rails/blob/3-2-stable/activerecord/lib/active_record/store.rb#L35
Now in 4.2.4, whether the data stored in serialized attribute is in YAML or JSON, the coder that is working for me now is YAML.
Hence my code was starting working after i changed the coder from JSON to YAML.
Any question/doubt about this answer will be appreciated.
来源:https://stackoverflow.com/questions/33539866/store-accessor-issue-cant-read-old-already-stored-json-object-serialized-ha