【问题标题】:in rails json rendering, how to show a different key name for a particular attribute在rails json渲染中,如何为特定属性显示不同的键名
【发布时间】:2012-02-04 21:43:25
【问题描述】:

我使用 Mongoid 作为后端,我需要返回带有“id”属性的 json,而不是 mongoid 使用的默认“_id”

例如,我现在有

[{
  "_id": "4f2d8b971773eb18e6000001",
  "name": "Scooter"
}, {
  "_id": "4f2d8d9f1773eb18fd000001",
  "name": "Coldplay"
}]

来自对渲染的调用:

  format.json { render :json => @groups, only:[:name, :_id] }

但需要,

[{
  "id": "4f2d8b971773eb18e6000001",
  "name": "Scooter"
}, {
  "id": "4f2d8d9f1773eb18fd000001",
  "name": "Coldplay"
}]

有什么捷径吗?

谢谢!!

【问题讨论】:

    标签: ruby-on-rails json mongoid render


    【解决方案1】:

    如果您能够为 _id 添加一个名为 id 的属性访问器,那么这应该可以通过在您的模型中覆盖 as_json 来轻松解决。

    def id
      self._id
    end
    
    def as_json(options={})
      options.merge!(:except => :_id, :methods => :id)
      super(options)
    end
    

    更新:使重写对父方法更加友好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多