-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Serialized ActiveRecord attributes serialize as empty hash #1908
Comments
@danderozier Interesting. I'm guessing the reason for that has to do with a bug in the Rails implementation of read_attribute_for_serialization for serialized fields. By the way, you probably want to use the JSON encoder for your field, based on what it looks like. It's faster and safer. What happens if you call |
@bf4 Thanks for the reply. |
FYI, you can also attributes :config do object.config end |
I can't think of anywhere that'd cause that kind of behavior. What's the backtrace(s) if you do the following?: class Widget < ApplicationRecord
serialize :config, Hash
+ def config
+ puts caller.join("\n\t")
+ self[:config].freeze
+ end |
If it helps, I've thrown together a demo app to exercise this bug: https://github.com/dummied/ams_1908_test_app Couple of observations:
Hope this helps! |
Looked into this a bit more and it's tied to the attribute name of
def read_attribute_for_serialization(attr)
if respond_to?(attr)
send(attr)
else
object.read_attribute_for_serialization(attr)
end
end In this case, Possible solutions that come to my mind:
I also explored switching to something like |
Also hit this bug with ActiveModelSerializers Version: 0.10.7 - @bf4, here is a failing test case: agalloch@a050aed
Workaround: |
Just ran into this issue this morning. @agalloch 's solution didn't work for me - I got I'm using the JSON::API adapter with AMS 0.10.7 Here is my workaround for the issue, it's far from elegant, but it works. class MySerializer < ActiveModel::Serializer
attributes :config
def config
cfg = object.config.clone
def cfg.jsonapi_use_foreign_key_on_belongs_to_relationship(*_)
nil
end
cfg
end
end |
Expected behavior vs actual behavior
Serializing serialized ActiveRecord Attributes (http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html) using AMS is failing. Expected behavior is for said attribute to appear in the serialized object, but instead appears as an empty hash.
Steps to reproduce
For example, take a model with a serialized attribute:
When serializing that model with AMS, the config attribute is an empty hash.
Whereas if I override :config with a method, it behaves as expected:
Environment
ActiveModelSerializers Version: 0.10.2
Output of
ruby -e "puts RUBY_DESCRIPTION"
: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]OS Type & Version: Mac OS 10.11.6
Integrated application and version (e.g., Rails, Grape, etc): Rails 5
The text was updated successfully, but these errors were encountered: