0

I have a User model and an Employment model like so:

Class User
 has_many :employments

Class Employment
 belongs_to :user

I'm serving up a JSON api via Active model serializer like so:

class EmploymentSerializer < ActiveModel::Serializer
  attributes :id
  has_one :user

class UserSerializer < ActiveModel::Serializer
  attributes :id

Everything works as it should. Here's the problem:

When the current_user is an employer, I'd load the employments with the user associations, which works fine. When the current_user is not an employer, I want to load the employments belonging to the user.

As the EmploymentSerializer has_one :user, this results in a recursive query where the current_user has_one employment has_one current_user ad infinitum.

I've tried adding this method in the EmploymentSerializer but it doesn't work:

def include_user?
  object.user != scope
end

How do I load the current_user's employments?


Solution

The recursion was caused by another serializer, and this question is irrelevant. AMS works as it should.

Ryan.lay
  • 1,741
  • 2
  • 17
  • 30

1 Answers1

1

With belongs_to, the table accepts the responsibility for the foreign key. With has_one, the table expect the other table to hold it. Since your Employments table has the foreign key to the Users table, has_one :user in the serializer doesn't make sense because it assumes that the Users table has the foreign key to the Employments table.

Generally, the serializer relationships should usually mirror the model, and you are mixing them up here. When your Employment class has a belongs_to :user relationship, your serializer should have the same one and not the opposite has_one relationship.

Edit: Ryan.lee's comment is correct. In active_model_serializers, has_one is indeed the same as belongs_to because serializers are concerned about multiplicity and now ownership. But since this is quite confusing because ActiveRecord, version 0.9 adds support for belongs_to too to mirror the ActiveRecord associations. So, using has_one in the serializer when the model has a belongs_to is indeed correct, but I would suggest to also use belongs_to in the serializer to avoid confusion since they mean the same thing in the context of the serializer (but not ActiveRecord!)

Community
  • 1
  • 1
p4sh4
  • 3,292
  • 1
  • 20
  • 33
  • 1
    AMS has_one indicates multiplicity and not ownership. It simply tells AMS which records to fetch. It is not the same as the Activerecord has_one relationship. – Ryan.lay May 05 '15 at 03:25
  • Which version of AMS are you using? – p4sh4 May 05 '15 at 03:27
  • 1
    0.10.0.rc1. As it turns out, the recursion was caused by another serializer, so I'll delete this question. Thanks for trying to help! – Ryan.lay May 05 '15 at 03:29