Serialization (and deserialization) of 'complex' Relay objects with JSON

This may be a stupid question, but I'm relatively new to Rails and wonder how Rails handles serializing the model with has_many (and / or belongs_to) objects of another class. Will it serialize the entire graph of the object by default? Do you really want this? Can you control it? How?

Any tricks on the receiving side regarding how to de-serialize it? or are quite a lot of brute force assigning properties to their hash value, and any built-in arrays / hashes will then become associated objects of the class?

Edit : Add the json example returned using the @zetetic example. Think about why the inline collection (grommets) has escape characters ( \) before each quote ( ")?

{"name":"Gizmo","height":15,"grommets":"[{\"name\":\"Sid\",\"color\":\"yellow\"},{\"name\":\"Elvis\",\"color\":\"\"},{\"name\":\"Teeny\",\"color\":\"Red\"}
+2
source share
2 answers

No, by default, serializing a model instance emits only its own attributes, not those of its associations. But you can customize this behavior by including a method in the model as_json:

class MyModel < ActiveRecord::Base
  has_many :widgets

  def as_json(options={})
    {
      :name => name,
      :widgets => widgets.to_json
    }
  end
end

You probably also want to define as_jsonin the associated model, otherwise you will get a standard attribute hash.

EDIT

, , . , as_json Widget, MyModel as_json :

def as_json(options={})
  {
    :name => name,
    :widgets => widgets.map(&:as_json)
  }
end

, monkeypatch Array # as_json , map.

, . :include .

+3

! ( Rails 2.3.8)

http://apidock.com/rails/ActiveRecord/Serialization/to_json

, : include

    konata.to_json(:include => :posts)
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true,
        "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
                  {"id": 2, author_id: 1, "title": "So I was thinking"}]}

. .

": has_many,: through".

+1

Source: https://habr.com/ru/post/1778366/


All Articles