首页 > 解决方案 > rails select查询为属性名称创建别名

问题描述

以创建 JSON 字符串为目标,要求是使用现有属性并在 JSON 输出中为其分配属性名称id

@valids = Destination.limit(10).select(:name, :long_name, :other_code).as_json(except: :id)  

except: :id正在调用以避免混淆,因为other_code属性旨在成为生成的 JSON 中的 id。

然后将通过以下方式将其转换为有效的 JSON

@valids.to_json 

如何other_code 输出为id

标签: ruby-on-railsjson

解决方案


您可以使用简单的字符串而不是符号来执行此操作。

Destination
  .limit(10)
  .select('name, long_name, other_code as id')
  .as_json

推荐阅读