2012-02-04 56 views
0

我使用Mongoid作为我的后端显示出不同的密钥名称,我需要用一个“id”返回JSON属性,而不是由mongoid使用默认的“_id”在轨JSON渲染,如何为特定属性

比如,我现在

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

有从呼叫渲染:

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

但需要,

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

任何快捷方式?

谢谢!

回答

1

如果你能添加一个属性访问器_id就称为id,那么这应该是很容易在你的模型覆盖as_json解决。

def id 
    self._id 
end 

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

更新:取得了超越多一点友好的父类的方法。