-1

Hello i am creating an API. I have a user and profile model. User has_one profile.

When i get a user end point i want to include the profile information(attributes) in the end point.

So far my end point looks like this

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

It should look like this

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

Here is my user serializer

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

Here is my show action in user controller

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
joeyk16
  • 1,357
  • 22
  • 49
  • If you are using AMS 0.9.3, you can pass options using #serialization_options, see http://stackoverflow.com/a/26780514/5086701 – beaorn Mar 08 '16 at 00:38

1 Answers1

0

The way it was set up is perfect. All i had to do was pass it in the uri

like this

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

In my show action params[:include] == "profile"

joeyk16
  • 1,357
  • 22
  • 49