【问题标题】:Rails Active Model Serializer - has_many and accessing the parent recordRails Active Model Serializer - has_many 和访问父记录
【发布时间】: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


    【解决方案1】:

    我会手动操作以获取控制权:

    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
    

    【讨论】:

    • 是的,这行得通,而且还不错。猜猜我太专注于通过“has_many”序列化程序选项实现它:)
    • 这个答案对我也很有帮助!不过我确实有一个问题。我正在做与 OP 非常相似的事情,但我将我与 embed: :ids, include: true 的关联嵌入到我所有的序列化程序中。当我手动创建序列化程序数组时,这些序列化程序没有嵌入的 id。似乎根本原因是将子序列化程序从关联更改为属性。我尝试过一些天真的事情,比如将embed: :ids 添加到初始化程序但没有成功。任何指导将不胜感激:)
    • @significance 不,不是我上次评论中提到的问题。我最终使用了一种解决方法来重组我的模型之间的关系。
    • @JaredMenard 是的,我倾向于提供所有选项(范围是一个非常重要的选项)以全面掌握该工具
    • @apneadiving 你能帮我解决这里提到的类似问题吗,stackoverflow.com/questions/44201299/…
    猜你喜欢
    • 2014-02-20
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多