【问题标题】:How To Include Model In JSON API output如何在 JSON API 输出中包含模型
【发布时间】:2016-03-08 00:10:33
【问题描述】:

您好,我正在创建一个 API。我有一个 userprofile 模型。用户 has_one 个人资料。

当我得到一个用户端点时,我想在端点中包含配置文件信息(属性)。

到目前为止,我的终点是这样的

 {
    "data" => {
      "id" => user.id.to_s,
      "type" => "users",
      "attributes" => {
        "email" => user.email
      },
      "relationships" => {
        "profile" => {
          "data" => {
            "id" => user.profile.id.to_s,
            "type" => "profiles"
          }
        }
      }
    }
  }

应该是这样的

  {
    "data" => {
      "id" => User.last.id.to_s,
      "type" => "users",
      "attributes" => {
        "email" => new_email
      },
      "relationships" => {
        "profile" => {
          "data" => {
            "id" => User.last.profile.id.to_s,
            "type" => "profiles"
          }
        }
      }
    }],
    "included": [
      {
        "type": "profiles",
        "id": "42",
        "attributes": {
          "first_name": "John",
          "last_name": "Smith"
        }
      }
    ]
  }

这是我的用户序列化程序

class UserSerializer < ActiveModel::Serializer
  attributes :email
  has_one :profile
end

这是我在用户控制器中的显示操作

module V1
  class UsersController < ApiController
    before_action :set_user, only: [:show, :update, :destroy]

    def show
      render json: @user, include: params[:include], status: :ok
    end


    private

    def set_user
      @user = User.find(params[:id])
    end

    def user_params
      attribute_params.permit(:email, :password, roles: [])
    end

    def assign_roles
    end
  end
end

【问题讨论】:

标签: ruby-on-rails ruby json ruby-on-rails-4


【解决方案1】:

它的设置方式非常完美。我所要做的就是在 uri 中传递它

喜欢这个

get "/v1/users?page[number]=1&amp;page[size]=3&amp;include=profile

在我的表演动作中 params[:include] == "profile"

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2021-09-30
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多