如何在JSON API输出中包含模型

时间:2016-03-08 00:10:33

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

您好我正在创建一个API。我有WHERE sub3.field1 = sub2.field1 AND sub3.field2 = sub2.field2...user模型。用户has_one个人资料。

当我得到用户终点时,我想在终点中包含个人资料信息(属性)。

到目前为止,我的终点看起来像这样

profile

看起来应该是这样的

 {
    "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"
        }
      }
    ]
  }

这是我在用户控制器中的show动作

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

1 个答案:

答案 0 :(得分:0)

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

像这样

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

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