Rails Active Model序列化器-has_many并访问父记录 [英] Rails Active Model Serializer - has_many and accessing the parent record

查看:97
本文介绍了Rails Active Model序列化器-has_many并访问父记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Active Model Serializer构建一些Rails模型的JSON表示,其中一些模型嵌入了其他模型.例如,我有事件和与会者,事件has_and_belongs_to_many与会者.

I'm trying to build a JSON representation of some Rails models using Active Model Serializer, where some models embed others. For example, I have Event and 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.

This would result in JSON like { name: 'Event One', attendees: [{ name: 'Alice' }, { name: 'Bob' }] }.

现在,我想补充一下与会者对活动的评价.比方说,Comment归属于事件,归属于参加者.我想在事件的序列化输出中包含所说的注释,因此它将变成{ name: 'Event One', attendees: [{ name: 'Alice', comments: [{ text: 'Event One was great!'}] }, { name: 'Bob', comments: [] }] }.

Now, I'd like to add what the attendees have said about the event. Let's say, Comment belongs_to Event, belongs_to Attendee. I'd like to include said comments in the serialized output of event, so it would become { 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

但这将选择此与会者针对所有事件的所有评论-不是我想要的.我想写这个,但是如何找到我要序列化的特定事件呢?我可以以某种方式访问​​父"对象,或者可以将选项传递给has_many序列化程序吗?

but that would select all the comments by this attendee for all the events - not what I want. I'd like to write this, but how do I find the particular event for which I'm doing serialization? Can I somehow access the 'parent' object, or maybe pass options to a has_many serializer?

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?

Is this something that can be done, or should I just build the JSON in another way for this particular use case?

推荐答案

我会手动做一些事情来获得控制权:

I'd do things manually to get control:

class EventSerializer < ActiveModel::Serializer
  attributes :name, :attendees

  def attendees
    object.attendees.map do |attendee|
      AttendeeSerializer.new(attendee, scope: scope, root: false, event: object)
    end
  end
end

class AttendeeSerializer < ActiveModel::Serializer
  attributes :name, :comments

  def comments
    object.comments.where(event_id: @options[:event].id).map do |comment|
      CommentSerializer.new(comment, scope: scope, root: false)
    end
  end
end

这篇关于Rails Active Model序列化器-has_many并访问父记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆