Answer the question
In order to leave comments, you need to log in
How to properly use AMS in complex json?
Good day, rails!
There was a question of using ActiveModelSerializer in complex json.
And so: ruby 2.4.1, rails 5.0.1
There is a User model that builds a Partnership with other users and can be either a User or a Partner.
class User < ApplicationRecord
has_many :partnerships, dependent: :destroy
has_many :partners, :through => :partnerships
belongs_to :partnership, class_name: 'Partnership' ,foreign_key: 'partner_id', required: false
end
class Partnership < ApplicationRecord
belongs_to :user, required: false
belongs_to :partner, class_name: 'User', required: false
end
class PartnershipSerializer < ActiveModel::Serializer
attributes :id, :user, :partner, :accepted
def user
user = object.user
{ id: user.id, full_name: user.full_name, foto: user.image}
end
def partner
partner = object.partner
{ id: partner.id, full_name: partner.full_name, foto: partner.image}
end
end
render json: {
inbox: {
accepted: Partnership.where(partner_id: current_user.id, accepted: true),
unaccepted: Partnership.where(partner_id: current_user.id, accepted: true))
}
}
PartnershipSerializer.new(Partnership.where(partner_id: current_user.id, accepted: true))
render json: {
inbox: {
accepted: ActiveModel::SerializableResource.new(@not_my.where(accepted: true)).as_json,
unaccepted: ActiveModel::SerializableResource.new(@not_my.where(accepted: false)).as_json
}}
Answer the question
In order to leave comments, you need to log in
ActiveModelSerializers::SerializableResource.new(Partnership.where(partner_id: current_user.id, accepted: true), { each_serializer: PartnershipSerializer })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question