Skip to content

Include doesn't work on nested associations in serializer #1972

Closed
@dnt294

Description

I've already posted this on Stackoverflow for more help, but I also post it here.


So I have models like this:

  • folder, up_file has 1 chat_room
  • chat_room belongs to crmable with polymorphic: true (so 1 chat_room may belongs to folder or 1 up_file)
  • chat_room has many comments
  • comment belongs to chat_room and user (who posted the comment)

I've defined all relationship like this:

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

I've follow their tutorial here but my associations not rendered.

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

All I got is this - chat_room association not serialized?

enter image description here

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions