Skip to content

Relationships with ActiveModelSerializers::Model #1961

@andrewferk

Description

@andrewferk

I'm using version 0.10.2 and attempting to create a relationship (belongs_to) with ActiveModelSerializers::Model (and not ActiveRecord::Model). The relationship output keeps returning null.

Thanks!

Model

class User::Registration < ActiveModelSerializers::Model

  attr_reader :user
  attr_accessor :email

  def save
    register_user
  end

  def email=(value)
    # Follow Devise's configuration to check if email is case insensitive
    @email = Devise.case_insensitive_keys.include?(:email) ? value.try(:downcase) : value
  end

  def id
    email
  end

  private

  def register_user
    @user = User.new(email: email)
    @user.provider = 'email'

    @user.send_confirmation_instructions if @user.save
    @user.clean_up_passwords

    @user.persisted?
  end
end

Resource

class User::RegistrationSerializer < ApplicationSerializer
  attributes :email
  belongs_to :user
end

Controller

def create
  @registration = User::Registration.new(email: @request[:email])
  @registration.save
  render json: @registration, status: :created
end

Ouptut

{"data": {"id":"[email protected]","type":"user-registrations","attributes":{"email":"[email protected]"},"relationships":{"user":{"data":null}}}}

I'd expect the relationships output to not be null.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions