ActiveModel JSON serialization

If you have code:

<%= JSON.pretty_generate(JSON.parse(@myobject.as_json)) %>

that results in "can't convert Hash into String"
Or

<%= JSON.pretty_generate(@myobject.as_json) %>

That results in: "undefined method `key?' for #"

Try:

<%= JSON.pretty_generate(JSON.parse(@page.to_json)) %>

And if as_json or to_json is not obeying your “only:”, “include:”, or “except:” directives, make sure you include ActiveModel’s JSON if your object is not an ActiveRecord object (or other object that inherits it already).

Along with that, you’ll need to implement an attributes method. As mentioned in ActiveModel::Serialization, “You need to declare some sort of attributes hash which contains the attributes you want to serialize and their current value.” The weird thing is that it doesn’t matter what the values returned in the hash are. It only obeys the keys, calling .send(key) on your object to get the value for each key.

class MyThing
  include ActiveModel::Serializers::JSON
  ...
  # Needed for ActiveModel::Serialization and things that use it (such as JSON)
  def attributes
    {
        'myattr' => nil,
        'anotherattr' => nil
    }
  end
end

One thought on “ActiveModel JSON serialization”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.