V
V
Vayladion Gognazdiak2018-01-30 21:14:41
Ruby on Rails
Vayladion Gognazdiak, 2018-01-30 21:14:41

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

Partnership Model
class Partnership < ApplicationRecord
  belongs_to :user, required: false
  belongs_to :partner, class_name: 'User', required: false
end

partnership serializer
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

Now directly about the "problem".
In the controller, I try to render the following json in response to a request
render json: { 
        inbox: { 
          accepted: Partnership.where(partner_id: current_user.id, accepted: true),
          unaccepted: Partnership.where(partner_id: current_user.id, accepted: true))
        }
}

Unfortunately, the serializer is not picked up, all the Partnership fields are returned, and not those specified in the serializer.
Using the following construct does nothing either:
PartnershipSerializer.new(Partnership.where(partner_id: current_user.id, accepted: true))

We get: NoMethodError (undefined method `read_attribute_for_serialization' for #):

Railsans, where to dig?
I did it through the ass, but I think there is a more elegant solution
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

1 answer(s)
A
Andrey Demidenko, 2018-01-31
@etspring

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 question

Ask a Question

731 491 924 answers to any question