ruby-on-rails - 如何在给定的上下文中表示对象属性?
问题描述
我正在寻找我的问题的解决方案我有一个关系 => Company
has_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
解决方案
不如为它定义一个代表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
)
推荐阅读
- reactjs - 按钮 - React Native
- powerbi - PowerBI 财政年度
- bash - 查找的 Bash 排序顺序 - 同名目录之前的文件
- amazon-cognito - 是否总是需要授权人:aws_iam?(使用身份池,支持非授权访问)
- python-3.x - Python Scipy Curvefit 到线性二次曲线
- c++ - 评估模板括号内的 constexpr
- mysql - mysql - 比较 date=n 和 date=n-1 的字符串值
- kubernetes - Kubernetes Pod 到 Pod 通信
- postgresql - 在 PostgreSQL 中存储过滤条件的最佳方式
- delphi - Delphi FMX 中的目录树视图