【问题标题】:Transform root association data Active Model Serializers 0.9.7转换根关联数据 Active Model Serializers 0.9.7
【发布时间】: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::RelationArray,你有一些Hash 代替那里。所以有一个合理的问题——你怎么称呼这个序列化器?
  • 类 CommentSerializer
  • index_by { |comment| comment["id"] } 呢?你能显示object.comments.first.keys的结果吗?
  • 我得到 NoMethodError: undefined method `keys' for #<0x00007f8d1b46bb80>
  • <0x00007f8d1b46bb80 id: content: to don giovanni book_id: created_at: sun jan utc>

标签: ruby-on-rails ruby active-model-serializers


【解决方案1】:

按以下方式更改BookSerializer#comments方法:

def comments object.comments.index_by { |c| c[:id] } end

【讨论】:

  • 仍然收到NoMethodError (undefined method id for #&lt;Hash:0x00007f8d19baca18&gt;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多