How to represent object properties in given context?

403 views Asked by At

I am looking for a solution to my problem I have a relation => Company has_many Councils, through CouncilCompany.

And I would like to display Company in context of given Council, so if CouncilCompany has name property present display it over default Company name.

# == Schema Information
#
# Table name: council_companies
#
#  id            :uuid             not null, primary key
#  name          :string
# == Schema Information
#
# Table name: companies
#
#  id                   :uuid             not null, primary key
#  name                 :string          default(FALSE), not null
render json: Company::Representer::Show.new(@company).to_json(
  current_user: current_api_v1_user,
  council: @council
)
require 'representable/json'
module Company::Representer
  class Show < Representable::Decorator
    include Representable::JSON

    Company.columns_hash.keys.each do |column|
      property column.to_sym.as_json, render_nil: true
    end
  end
end

What would be the best way to do that? Tried already to find solution here: https://trailblazer.to/2.1/docs/representable.html#representable-api

1

There are 1 answers

0
Yogesh Khater On BEST ANSWER

How about defining a representer for CouncilCompany instead, as it belongs to Company ?

require 'representable/json'

module CouncilCompany::Representer
  class Show < Representable::Decorator
    include Representable::JSON

    property :name, default: -> { company.name }

    property :company do
      property :id
      property :name
      ...
    end
  end
end
render json: CouncilCompany::Representer::Show.new(@council_company).to_json(
  current_user: current_api_v1_user
)