【发布时间】:2014-09-20 13:03:02
【问题描述】:
我正在尝试使用 Active Model Serializer 构建一些 Rails 模型的 JSON 表示,其中一些模型嵌入了其他模型。例如,我有 Event 和 Attendees,Event has_and_belongs_to_many Attendees。
class EventSerializer < ActiveModel::Serializer
attributes :name
has_many :attendees, serializer: AttendeeSerializer
end
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
end
这将产生类似{ name: 'Event One', attendees: [{ name: 'Alice' }, { name: 'Bob' }] } 的 JSON。
现在,我想补充一下与会者对此次活动的看法。比方说,评论belongs_to Event,belongs_to Attendee。我想将上述 cmets 包含在事件的序列化输出中,因此它将变为 { name: 'Event One', attendees: [{ name: 'Alice', comments: [{ text: 'Event One was great!'}] }, { name: 'Bob', comments: [] }] }。
我本来可以
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
end
但这会为所有活动选择此参与者的所有 cmets - 这不是我想要的。我想写这篇文章,但是如何找到我正在为其进行序列化的特定事件?我可以以某种方式访问“父”对象,或者将选项传递给 has_many 序列化程序吗?
class AttendeeSerializer < ActiveModel::Serializer
attributes :name
has_many :comments
def comments
object.comments.where(event_id: the_event_in_this_context.id)
end
end
这是可以做到的,还是我应该为这个特定用例以另一种方式构建 JSON?
【问题讨论】:
标签: ruby-on-rails json active-model-serializers