首页 > 解决方案 > 如何在给定的上下文中表示对象属性?

问题描述

我正在寻找我的问题的解决方案我有一个关系 => Companyhas_many Councils,通过CouncilCompany.

而且我想在给定委员会的上下文中显示 Company,因此如果CouncilCompany存在name属性,则将其显示在 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

最好的方法是什么?已经尝试在这里找到解决方案:https ://trailblazer.to/2.1/docs/representable.html#representable-api

标签: ruby-on-railsdecoratortrailblazerrepresentable

解决方案


不如为它定义一个代表CouncilCompany,因为它属于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
)

推荐阅读