【发布时间】:2018-02-16 14:52:11
【问题描述】:
我基本上是尝试使用活动模型序列化程序返回一些数据,使用键值对对象而不是我的关联数组。所以,而不是
{
books: [{
id: 1,
title: "Foo"
}],
comments: [...]
}
我想要
{
books: [{
id: 1,
title: "Foo"
}],
comments: {
"1": {
id: 1,
content: "Bar"
}
}
}
到目前为止,我正在做的是,但我得到: NoMethodError(# Hash:0x00007f8d1b24d100 的未定义方法“id”):
class BookSerializer < ActiveModel::Serializer
attributes :id, :title, :description, :created_by, :created_at
has_many :comments
def comments
object.comments.index_by(&:id)
end
end
我正在使用 AMS 0.9.7 和 rails 5.0
【问题讨论】:
-
什么返回
object.comments?我想,你没有ActiveRecord::Relation或Array,你有一些Hash代替那里。所以有一个合理的问题——你怎么称呼这个序列化器? -
类 CommentSerializer
-
index_by { |comment| comment["id"] }呢?你能显示object.comments.first.keys的结果吗? -
我得到 NoMethodError: undefined method `keys' for #<0x00007f8d1b46bb80>0x00007f8d1b46bb80>
- <0x00007f8d1b46bb80 id: content: to don giovanni book_id: created_at: sun jan utc>0x00007f8d1b46bb80>
标签: ruby-on-rails ruby active-model-serializers