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