【发布时间】:2018-04-04 01:31:34
【问题描述】:
我在我的项目中使用Rails 5 和Acive Model Serializer (0.10.6)。我需要以下格式的 JSON
{
"account_lists": {
"0": {
"id": 1,
"description": "test tets test tets"
},
"1": {
"id": 2,
"description": "test tets test tets"
}
}
}
0,1 键是对象的索引。
我尝试了下面的代码,但结果不出来
account_serializer.rb
class AccountSerializer < ActiveModel::Serializer
attributes :custom_method
def custom_method
{ object.id => {id: object.id, description: object. description } }
end
end
accounts_controller.rb
render json: @accounts, root: "account_lists", adapter: :json
结果是
{
"account_lists": [
{
"custom_method": {
"46294": {
"id": 46294,
"description": "test tets test tets"
}
}
},
{
"custom_method": {
"46295": {
"id": 46295,
"description": "test tets test tets"
}
}
]
}
你能帮我得到结果吗?
【问题讨论】:
-
如果不需要root,可以将root设置为false。像这样
render json: @accounts, root: false, adapter: :json -
@SujayGavhane 我需要根目录,但我想要对象根目录的自定义根目录。
-
@Jenorish 你知道了吗,我只需要像这样工作。
-
@7urkm3n 还没试过。
-
@Jenorish 你遇到什么样的错误?
标签: ruby-on-rails serialization ruby-on-rails-5 active-model-serializers