在Rails中序列化嵌套属性?

时间:2016-11-12 15:44:50

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

所以我有这样的模特:

  • folderup_file有1 chat_room
  • chat_room属于crmable,具有多态:true(因此1 chat_room可能属于folder或1 up_file
  • chat_room有很多comments
  • comment属于chat_roomuser(发表评论的人)

我已经定义了所有这样的关系:

class Folder < ApplicationRecord
    has_one :chat_room, as: :crmable, dependent: :destroy
end

class UpFile < ApplicationRecord
    has_one :chat_room, as: :crmable, dependent: :destroy
end

class ChatRoom < ApplicationRecord
    belongs_to :crmable, polymorphic: true

    has_many :comments, dependent: :destroy
    has_many :users, through: :comments
end

class Comment < ApplicationRecord
    belongs_to :chat_room
    belongs_to :user
end

此设置适用于我的网络应用。但是,我正在为这个应用程序编写API,而且我无法获得与此gem序列化的嵌套关联

https://github.com/rails-api/active_model_serializers

我已按照他们的教程here进行操作,但未呈现我的关联。

class FolderSerializer < ActiveModel::Serializer

    attributes :id, :name, :ancestry, :creator_name #... my other attributes

    has_one :chat_room, include: [ :id, comments: :user ]
    # ^ I tried to serialize folder's chat_room with all it comments, along with these comments' users.
end

我得到的是这个 - chat_room关联没有序列化?

enter image description here

0 个答案:

没有答案