跳到內容 跳到搜尋

Active Model JSON 序列化器

方法
A
F
包含的模組

實例公開的方法

as_json(options = nil)

傳回表示模型的雜湊。某些組態可以透過 options 傳遞。

include_root_in_json 選項控制 as_json 的頂層行為。如果是 trueas_json 會發出單一根節點,名稱會根據物件的類型而定。include_root_in_json 選項的預設值是 false

user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#     "created_at" => "2006-08-01T17:27:133.000Z", "awesome" => true}

ActiveRecord::Base.include_root_in_json = true

user.as_json
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

也可以設定 :root 選項為 true 來達成此行為,如下所示

user = User.find(1)
user.as_json(root: true)
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

如果你偏好,:root 也可以設定為自訂字串金鑰,如下所示

user = User.find(1)
user.as_json(root: "author")
# => { "author" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true } }

沒有任何 options 的話,傳回的 雜湊 將會包含模型的所有屬性。

user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true}

:only:except 選項可以用來限制包含的屬性,運作方式類似於 attributes 方法。

user.as_json(only: [:id, :name])
# => { "id" => 1, "name" => "Konata Izumi" }

user.as_json(except: [:id, :created_at, :age])
# => { "name" => "Konata Izumi", "awesome" => true }

要包含模型中某些方法呼叫的結果,請使用 :methods

user.as_json(methods: :permalink)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "permalink" => "1-konata-izumi" }

要包含關聯,請使用 :include

user.as_json(include: :posts)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
#                   { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }

二階和高階關聯也可以運作

user.as_json(include: { posts: {
                           include: { comments: {
                                          only: :body } },
                           only: :title } })
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true,
#      "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
#                     "title" => "Welcome to the weblog" },
#                   { "comments" => [ { "body" => "Don't think too hard" } ],
#                     "title" => "So I was thinking" } ] }
# File activemodel/lib/active_model/serializers/json.rb, line 96
def as_json(options = nil)
  root = if options && options.key?(:root)
    options[:root]
  else
    include_root_in_json
  end

  hash = serializable_hash(options).as_json
  if root
    root = model_name.element if root == true
    { root => hash }
  else
    hash
  end
end

from_json(json, include_root = include_root_in_json)

根據 JSON 字串設定模型 屬性。傳回 self

class Person
  include ActiveModel::Serializers::JSON

  attr_accessor :name, :age, :awesome

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def attributes
    instance_values
  end
end

json = { name: 'bob', age: 22, awesome:true }.to_json
person = Person.new
person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name            # => "bob"
person.age             # => 22
person.awesome         # => true

include_root 的預設值是 false。如果指定的 JSON 字串包含單一根節點,你可以將它變更為 true

json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
person = Person.new
person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
person.name                  # => "bob"
person.age                   # => 22
person.awesome               # => true
# File activemodel/lib/active_model/serializers/json.rb, line 146
def from_json(json, include_root = include_root_in_json)
  hash = ActiveSupport::JSON.decode(json)
  hash = hash.values.first if include_root
  self.attributes = hash
  self
end