Active model serializer association unless object.user == current_user

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

How do I load the current_user's employments?


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


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!)

Need Your Help

Selenium connection time out when initializing driver

python django selenium selenium-webdriver browserstack

I've written a Django (version 1.3, sadly) management command to connect to BrowserStack with Selenium and am going to be using to run integration tests. (I've had to write a custom management comm...

choice between map or unordered_map for keys consisting of calculated double values.

c++ dictionary hash unordered-map comparison-operators

In order to quickly find coplanar entities in a bunch of planar entities in 3d space, I want to create a mapping from 3d planes to the set of entities lying in that plane (estimated max around ~1000